/**
 * 
 */
package org.springblade.etl.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.etl.dto.JobPermissionDoo;
import org.springblade.etl.dto.JobPermissionDto;
import org.springblade.etl.entity.SqlJob;
import org.springblade.etl.entity.SqlJobPermission;
import org.springblade.etl.mapper.SqlJobPermissionMapper;
import org.springblade.system.client.DataPermClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 *	SQL任务权限组 服务处理
 *
 * @author aokunsang
 * @date   2023-12-03
 */
@Service
public class SqlJobPermissionService extends ServiceImpl<SqlJobPermissionMapper, SqlJobPermission>{

	@Autowired
	private DataPermClient dataPermClient;
	
	@Autowired
	private SqlJobService sqlJobService;
	
	/**
	 * 访问权限
	 * @param visualCreateUserId
	 * @param bladeUser
	 * @return
	 */
	public boolean checkJobDataForUser(Integer jobId, Long visualCreateUserId, BladeUser bladeUser) {
		//检查4个方面：
		//1.当前用户是否创建人
		//2.是否公开
		//3.是否超级权限组
		//4.当前用户是否拥有权限
		return  visualCreateUserId.longValue() == bladeUser.getUserId()
				|| sqlJobService.count(Wrappers.<SqlJob>lambdaQuery().eq(SqlJob::getId, jobId).eq(SqlJob::getPublicStatus, 1)) > 0
				|| Optional.<Boolean>ofNullable(dataPermClient.checkSuperPermission(bladeUser.getUserId())).orElse(false)
				|| baseMapper.checkJobForUser(jobId, bladeUser.getUserId()) > 0;
	}
	
	/**
	 * 权限组管理入口 
	 * @param visualDataPermDto
	 * @return
	 */
	@Transactional
	public boolean doSaveOrUpdate(JobPermissionDto jobPermissionDto, BladeUser bladeUser) {
		//通过关联删除，删除分类ID的数据
		baseMapper.deleteByCategoryIdAndPermId(jobPermissionDto.getJobCategoryId(), jobPermissionDto.getDataPermId());
		//2.再添加
		if(CollectionUtil.isNotEmpty(jobPermissionDto.getJobIdList())) {
			//更新公开状态为0[否则权限组不生效]
			sqlJobService.update(Wrappers.<SqlJob>lambdaUpdate().set(SqlJob::getPublicStatus, 0).in(SqlJob::getId, jobPermissionDto.getJobIdList()));
			List<SqlJobPermission> dataList = new ArrayList<>(jobPermissionDto.getJobIdList().size());
			jobPermissionDto.getJobIdList().forEach(t -> {
				SqlJobPermission entity = new SqlJobPermission();
				entity.setCreateBy(bladeUser.getNickName());
				entity.setCreateTime(new Date());
				entity.setCreateUserId(bladeUser.getUserId());
				entity.setDataPermId(jobPermissionDto.getDataPermId());
				entity.setJobId(t);
				dataList.add(entity);
			});
			saveBatch(dataList);
		}
		return true;
	}
	
	/**
	 * 任务流程列表的权限组管理入口
	 * @param visualDataPermDoo
	 * @param bladeUser
	 * @return
	 */
	@Transactional
	public boolean doPerform(JobPermissionDoo jobPermDoo, BladeUser bladeUser) {
		//1.根据任务ID删除所属权限组
		baseMapper.delete(Wrappers.<SqlJobPermission>lambdaQuery().eq(SqlJobPermission::getJobId, jobPermDoo.getJobId()));
		if(jobPermDoo.getPublicStatus() != null) {
			sqlJobService.update(Wrappers.<SqlJob>lambdaUpdate().set(SqlJob::getPublicStatus, jobPermDoo.getPublicStatus()).eq(SqlJob::getId, jobPermDoo.getJobId()));
		}
		//2.批量添加权限组
		if(CollectionUtil.isNotEmpty(jobPermDoo.getDataPermIdList())) {
			List<SqlJobPermission> dataList = new ArrayList<>(jobPermDoo.getDataPermIdList().size());
			jobPermDoo.getDataPermIdList().forEach(dataPermId -> {
				SqlJobPermission entity = new SqlJobPermission();
				entity.setCreateBy(bladeUser.getNickName());
				entity.setCreateTime(new Date());
				entity.setCreateUserId(bladeUser.getUserId());
				entity.setDataPermId(dataPermId);
				entity.setJobId(jobPermDoo.getJobId());
				dataList.add(entity);
			});
			saveBatch(dataList);
		}
		return true;
	}
	
	/**
	 * 
	 * @param dataPermId
	 * @param classifyId
	 * @return
	 */
	public List<Integer> listJobId(Integer dataPermId, Integer categoryId){
		return baseMapper.selectJobIdList(categoryId, dataPermId);
	}
	
	/**
	 * 
	 * @param visualId
	 * @return
	 */
	public List<JSONObject> listDataPerm(Integer visualId){
		return baseMapper.selectDataPermList(visualId);
	}
}