package org.springblade.audit.controller;


import java.util.HashMap;
import java.util.List;

import org.springblade.audit.entity.BladeReportTask;
import org.springblade.audit.service.IBladeReportTaskService;
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.system.client.UserClient;
import org.springblade.system.client.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 任务表 前端控制器
 * </p>
 *
 * @author zbc
 * @since 2021-12-14
 */
@RestController
@RequestMapping("/audit/reportTask")
@Api(value = "报表任务管理", tags = "报表任务接口")
@Slf4j
public class BladeReportTaskController {

	@Autowired
	private IBladeReportTaskService bladeReportTaskService;

	@Autowired
	private UserClient userClient;

	@GetMapping("/page")
	@ApiOperation(value = "任务列表")
	public R page(Query query) {
		Long userId = SecureUtil.getUserId();
		IPage<BladeReportTask> page = Condition.getPage(query);
		IPage<BladeReportTask> pages = bladeReportTaskService.getPageByQuery(page, userId);
		List<BladeReportTask> records = pages.getRecords();
		for (BladeReportTask record : records) {
			UserModel audit = userClient.getById(record.getCreateUser());
			record.setUserName(audit.getRealName());
		}
		int count = bladeReportTaskService.count(new LambdaQueryWrapper<BladeReportTask>()
			.eq(BladeReportTask::getDownloadStatus, 1)
			.eq(BladeReportTask::getCreateUser,userId)
		);
		HashMap<String, Object> map = new HashMap<>();
		map.put("data",pages);
		map.put("num",count);
		return R.data(map);
	}

	@PostMapping("/editDownloadStatus")
	@ApiOperation(value = "修改下载状态")
	public R update(Long id) {
		BladeReportTask task = bladeReportTaskService.getById(id);
		if(task == null){
			return R.fail("下载数据不存在");
		}
		task.setDownloadStatus(2);
		return R.status(bladeReportTaskService.updateById(task));
	}

}

