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

import java.time.LocalDateTime;
import java.util.List;

import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.etl.entity.Job;
import org.springblade.etl.entity.JobCategory;
import org.springblade.etl.service.JobCategoryService;
import org.springblade.etl.service.JobService;
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.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 *	任务分类 操作处理
 *
 * @author aokunsang
 * @date   2023-07-28
 */
@RestController
@RequestMapping("/job-category")
@Api(value = "任务分类相关接口", tags = "任务分类接口")
public class JobCategoryController extends BladeController {

	@Autowired
	private JobCategoryService jobCategoryService;
	
	@Autowired
	private JobService jobService;
	
	@Autowired
	private DataPermClient dataPermClient;
	
	/**
	 * 	列表数据
	 * @param jobCategory
	 * @return
	 */
	@GetMapping("/page")
	@ApiOperation(value = "分页查询任务分类", httpMethod = "GET")
	public R<IPage<JobCategory>> pageList(JobCategory jobCategory, Query query){
		QueryWrapper<JobCategory> queryWrapper = Condition.getQueryWrapper(jobCategory);
		return R.data(jobCategoryService.page(Condition.getPage(query), queryWrapper.lambda().orderByDesc(JobCategory::getId)));
	}
	
	/**
	 * 
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "查询任务流程分类列表", notes = "传入jobCategory")
	public R<List<JobCategory>> list(JobCategory jobCategory) {
		QueryWrapper<JobCategory> queryWrapper = Condition.getQueryWrapper(jobCategory);
		long currUserId = getUser().getUserId();
		List<JobCategory> dataList = jobCategoryService.list(queryWrapper.lambda().orderByDesc(JobCategory::getSortNum).orderByDesc(JobCategory::getId));
		Boolean checkSuperPermRet = dataPermClient.checkSuperPermission(currUserId);
		if(checkSuperPermRet != null && checkSuperPermRet) { //是否有超级权限
			return R.data(dataList);
		}else {
			//查询所有任务有权限的分类ID集合
			List<Integer> categoryIdList = jobService.categoryIdListOfPerm(currUserId);
			//1.获取这些分类的父级ID[包含自己创建的分类父级别ID]
			dataList.stream().filter(f -> (categoryIdList.contains(f.getId()) || f.getCreateUserId().longValue() == currUserId) && f.getParentId() != 0).map(JobCategory::getParentId).forEach(categoryIdList::add);
			//2.删除不在权限内的分类[且createUserId不是本人的]
			dataList.removeIf(y -> !categoryIdList.contains(y.getId()) && y.getCreateUserId().longValue() != currUserId);
			return R.data(dataList);
		}
	}
	
	/**
	 * 单条数据查询接口
	 * @param id
	 * @return
	 */
	@GetMapping("/info")
	@ApiOperation(value = "根据ID获取任务分类", httpMethod = "GET")
	public R<JobCategory> info(@RequestParam Integer id) {
		return R.data(jobCategoryService.getById(id));
	}
	
	/**
	 *	修改数据接口
	 * @param jobCategory
	 * @return
	 */
	@ApiLog("ETL任务分类")
	@PostMapping("/submit")
	@ApiOperation(value = "增加或修改任务分类", httpMethod = "POST")
	public R<String> doUpdate(@Validated @RequestBody JobCategory jobCategory) {
		//判重
		List<JobCategory> list = jobCategoryService.lambdaQuery()
				.eq(JobCategory::getCateName, jobCategory.getCateName())
				.ne(jobCategory.getId() != null, JobCategory::getId, jobCategory.getId()).list();
		if (CollectionUtil.isNotEmpty(list)) return R.fail("名字重复");
		if(jobCategory.getId() == null) {
			jobCategory.setCreateTime(LocalDateTime.now());
			jobCategory.setCreateUserId(AuthUtil.getUserId());
			jobCategory.setCreateBy(AuthUtil.getNickName());
		}
		return R.status(jobCategoryService.saveOrUpdate(jobCategory));
	}
	
	/**
	 * 	删除数据接口
	 * @param id
	 * @return
	 */
	@ApiLog("ETL任务分类")
	@PostMapping("/delete")
	@ApiOperation(value = "根据ID删除任务分类", httpMethod = "POST")
	public R<String> doDelete(@RequestParam Integer id) {
		long cnt = jobService.count(Wrappers.<Job>lambdaQuery()
			.eq(Job::getCategoryId, id));
		if(cnt > 0) {
			return R.fail("该分类下有任务，不能删除。");
		}
		long count = jobCategoryService.count(Wrappers.<JobCategory>lambdaQuery().eq(JobCategory::getParentId, id));
		if(count > 0) {
			return R.fail("该分类下有子分类，不能删除。");
		}
		return R.status(jobCategoryService.removeById(id));
	}
	
}