///*
// *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
// *
// *  Redistribution and use in source and binary forms, with or without
// *  modification, are permitted provided that the following conditions are met:
// *
// *  Redistributions of source code must retain the above copyright notice,
// *  this list of conditions and the following disclaimer.
// *  Redistributions in binary form must reproduce the above copyright
// *  notice, this list of conditions and the following disclaimer in the
// *  documentation and/or other materials provided with the distribution.
// *  Neither the name of the dreamlu.net developer nor the names of its
// *  contributors may be used to endorse or promote products derived from
// *  this software without specific prior written permission.
// *  Author: Chill 庄骞 (smallchill@163.com)
// */
//package org.springblade.etl.controller.bi;
//
//import java.util.List;
//import java.util.UUID;
//
//import javax.validation.Valid;
//
//import org.apache.commons.collections4.CollectionUtils;
//import org.springblade.core.boot.ctrl.BladeController;
//import org.springblade.core.mp.support.Condition;
//import org.springblade.core.mp.support.Query;
//import org.springblade.core.secure.utils.SecureUtil;
//import org.springblade.core.tool.api.R;
//import org.springblade.core.tool.utils.Func;
//import org.springblade.datasource.enums.DsTypeEnum;
//import org.springblade.datasource.support.DynamicDataSourceSupport;
//import org.springblade.etl.entity.ReportDatasource;
//import org.springblade.etl.entity.ReportDatasourcePermission;
//import org.springblade.etl.service.ReportDatasourcePermissionService;
//import org.springblade.etl.service.ReportDatasourceService;
//import org.springblade.system.client.DataPermClient;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.validation.annotation.Validated;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestBody;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestParam;
//import org.springframework.web.bind.annotation.RestController;
//
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.baomidou.mybatisplus.core.metadata.IPage;
//import com.baomidou.mybatisplus.core.toolkit.Wrappers;
//import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
//
//import cn.hutool.core.util.StrUtil;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiParam;
//import lombok.extern.slf4j.Slf4j;
//
///**
// * 报表数据源 控制器
// *
// * @author BladeX
// * @since 2021-03-22
// */
//@Slf4j
//@RestController
//@RequestMapping("report/reportdatasource")
//@Api(value = "报表数据源", tags = "报表数据源")
//public class ReportDatasourceController extends BladeController {
//
//	@Autowired
//	private ReportDatasourceService reportDatasourceService;
//
//	@Autowired
//	private DynamicDataSourceSupport dynamicDataSourceSupport;
//
//	@Autowired
//	private ReportDatasourcePermissionService reportDatasourcePermissionService;
//
//	@Autowired
//	private DataPermClient dataPermClient;
//
//	private final static String DEFAULT_ENCRYPT_PASSWORD = "******";
//
//	/**
//	 * 详情
//	 */
//	@GetMapping("/detail")
//	@ApiOperationSupport(order = 1)
//	@ApiOperation(value = "详情 detail", notes = "传入reportDatasource")
//	public R<ReportDatasource> detail(ReportDatasource reportDatasource) {
//		ReportDatasource detail = reportDatasourceService.getOne(Condition.getQueryWrapper(reportDatasource));
//		return R.data(detail);
//	}
//
//	/**
//	 * 分页 报表数据源
//	 */
//	@GetMapping("/list")
//	@ApiOperationSupport(order = 2)
//	@ApiOperation(value = "列表 list", notes = "传入reportDatasource")
//	@Deprecated
//	public R<List<ReportDatasource>> list(ReportDatasource reportDatasource) {
//		Long userId = getUser().getUserId();
//		LambdaQueryWrapper<ReportDatasource> queryWrapper = Condition.getQueryWrapper(reportDatasource).lambda().orderByDesc(ReportDatasource::getId);
//		Boolean checkSuperPermRet = dataPermClient.checkSuperPermission(userId);
//		if(checkSuperPermRet == null || !checkSuperPermRet) {
//			queryWrapper.and(t ->{
//				t.eq(ReportDatasource::getCreateUserId, userId)
//				.or().inSql(ReportDatasource::getId, "SELECT a.datasource_id FROM report_datasource_permission a INNER JOIN data_permission_user b ON a.data_perm_id=b.data_perm_id WHERE b.user_id=" + userId);
//			});
//		}
//		List<ReportDatasource> dataList = reportDatasourceService.list(queryWrapper);
//		if(CollectionUtils.isNotEmpty(dataList)) {
//			dataList.forEach(item -> item.setDsPassword(DEFAULT_ENCRYPT_PASSWORD));
//		}
//		return R.data(dataList);
//	}
//
//	/**
//	 * 自定义分页 报表数据源
//	 */
//	@GetMapping("/page")
//	@ApiOperationSupport(order = 3)
//	@ApiOperation(value = "分页 page", notes = "传入reportDatasource")
//	public R<IPage<ReportDatasource>> page(ReportDatasource reportDatasource, Query query) {
//		Long userId = getUser().getUserId();
//		LambdaQueryWrapper<ReportDatasource> queryWrapper = Condition.getQueryWrapper(reportDatasource).lambda().orderByDesc(ReportDatasource::getId);
//		Boolean checkSuperPermRet = dataPermClient.checkSuperPermission(userId);
//		if(checkSuperPermRet == null || !checkSuperPermRet) {
//			queryWrapper.and(t ->{
//				t.eq(ReportDatasource::getCreateUserId, userId)
//				.or().inSql(ReportDatasource::getId, "SELECT a.datasource_id FROM report_datasource_permission a INNER JOIN data_permission_user b ON a.data_perm_id=b.data_perm_id WHERE b.user_id=" + userId);
//			});
//		}
//		IPage<ReportDatasource> page = reportDatasourceService.page(Condition.getPage(query), queryWrapper);
//		if(page != null && CollectionUtils.isNotEmpty(page.getRecords())) {
//			page.getRecords().forEach(item -> item.setDsPassword(DEFAULT_ENCRYPT_PASSWORD));
//		}
//		return R.data(page);
//	}
//
//	/**
//	 * 新增 报表数据源
//	 */
//	@PostMapping("/save")
//	@ApiOperationSupport(order = 4)
//	@ApiOperation(value = "新增 save", notes = "传入reportDatasource")
//	public R<?> save(@Valid @RequestBody ReportDatasource dto) {
//		DsTypeEnum dsTypeEnum = DsTypeEnum.resolve(dto.getDsType());
//		dto.setDriverClassName(dsTypeEnum.getDriverClassName());
////		dto.setUrl(dsTypeEnum.createUrl(dto.getDsIp(), dto.getDsPort(), dto.getDsDb()));
//		dto.setUrl(dsTypeEnum.getDriverUrlFunction().apply(dto));
//		dto.setCreateUserId(getUser().getUserId());
//		//oracle/dameng的schema默认是用户名
//		dto.setDbSchema((dsTypeEnum == DsTypeEnum.oracle || dsTypeEnum == DsTypeEnum.dameng)  && StrUtil.isBlank(dto.getDbSchema()) ? dto.getDsUser() : dto.getDbSchema());
//		//设置默认poolName
//		dto.setPoolName(UUID.randomUUID().toString().replaceAll("-", "").substring(0, 10));
//		//ETL默认不添加数据源到连接池【使用懒加载模式】
////		boolean addDsRet = dynamicDataSourceSupport.addDs(dto);
//		return R.status(DynamicDataSourceSupport.testDs(dto) && reportDatasourceService.save(dto));
//	}
//
//	/**
//	 * 修改 报表数据源
//	 */
//	@PostMapping("/update")
//	@ApiOperationSupport(order = 5)
//	@ApiOperation(value = "修改 update", notes = "传入reportDatasource")
//	public R<?> update(@Valid @RequestBody ReportDatasource dto) {
//		if(dto.getId() == null || dto.getId() <= 0) {
//			return R.fail("数据源ID不能为空");
//		}
//		ReportDatasource dbReportDs = reportDatasourceService.getById(dto.getId());
//		if(dbReportDs == null) {
//			return R.fail("数据源不存在");
//		}
//		DsTypeEnum dsTypeEnum = DsTypeEnum.resolve(dto.getDsType());
//		dto.setDriverClassName(dsTypeEnum.getDriverClassName());
//		dto.setUrl(dsTypeEnum.getDriverUrlFunction().apply(dto));
//		dto.setDbSchema(dsTypeEnum == DsTypeEnum.oracle && StrUtil.isBlank(dto.getDbSchema()) ? dto.getDsUser() : dto.getDbSchema());
//		try {
//			//先删除，再添加
//			dynamicDataSourceSupport.removeDs(dbReportDs.getPoolName());
//			log.info("Delete:DataSource|dbname={}, operator={}", dto.getDsDb(), SecureUtil.getUserName());
//			dto.setPoolName(dbReportDs.getPoolName());
//			if(DEFAULT_ENCRYPT_PASSWORD.equals(dto.getDsPassword())) {
//				dto.setDsPassword(dbReportDs.getDsPassword());
//			}
//			//ETL默认不添加数据源到连接池【使用懒加载模式】
////			boolean ret = dynamicDataSourceSupport.addDs(dto);
//			return R.status(DynamicDataSourceSupport.testDs(dto) && reportDatasourceService.updateById(dto));
//		} catch (Exception e) {
//			log.error(e.getMessage(), e);
//			return R.fail("修改数据源失败");
//		}
//	}
//
//
//	/**
//	 * 删除 报表数据源
//	 */
//	@PostMapping("/remove")
//	@ApiOperationSupport(order = 6)
//	@ApiOperation(value = "删除 remove", notes = "传入ids")
//	public R<?> remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
//		List<Long> idList = Func.toLongList(ids);
//		List<ReportDatasource> reportDsList = reportDatasourceService.listByIds(idList);
//		for(ReportDatasource dto : reportDsList) {  //先移除数据源，再删除报表
//			try {
//				dynamicDataSourceSupport.removeDs(dto.getPoolName());
//				log.info("Delete:DataSource|dbname={}, operator={}", dto.getDsDb(), SecureUtil.getUserName());
//			} catch (Exception e) {
//				log.error(e.getMessage(), e);
//			}
//		}
//		List<Long> dsIds = Func.toLongList(ids);
//		reportDatasourcePermissionService.remove(Wrappers.<ReportDatasourcePermission>lambdaQuery().in(ReportDatasourcePermission::getDatasourceId, dsIds));
//		return R.status(reportDatasourceService.removeByIds(dsIds));
//	}
//
//	/**
//	 * 测试数据源
//	 * @param dto
//	 * @return
//	 */
//	@PostMapping("/testDs")
//	@ApiOperationSupport(order = 7)
//	@ApiOperation(value = "测试数据源 testDs", notes = "传入数据源信息")
//	public R<?> testDs(@Validated @RequestBody ReportDatasource dto) {
//		//解决更新页面，密码是加密导致的测试数据源失败
//		if(DEFAULT_ENCRYPT_PASSWORD.equals(dto.getDsPassword())) {
//			ReportDatasource dbReportDs = reportDatasourceService.getById(dto.getId());
//			if(dbReportDs != null) {
//				dto.setDsPassword(dbReportDs.getDsPassword());
//			}
//		}
//		DsTypeEnum dsTypeEnum = DsTypeEnum.resolve(dto.getDsType());
//		dto.setUrl(dsTypeEnum.getDriverUrlFunction().apply(dto));
//		boolean testDs = DynamicDataSourceSupport.testDs(dto);
//		return testDs ? R.success("连接成功") : R.fail("连接失败,请检查");
//	}
//}
