package org.jeecg.modules.task.controller;

import org.jeecg.common.system.query.QueryGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import java.util.Arrays;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.task.entity.CsPtTaskmx;
import org.jeecg.modules.task.entity.CsPtTask;
import org.jeecg.modules.task.service.ICsPtTaskService;
import org.jeecg.modules.task.service.ICsPtTaskmxService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 异步任务
 * @Author: jeecg-boot
 * @Date:   2023-11-29
 * @Version: V1.0
 */
@Api(tags="异步任务")
@RestController
@RequestMapping("/task/csPtTask")
@Slf4j
public class CsPtTaskController extends JeecgController<CsPtTask, ICsPtTaskService> {

	@Autowired
	private ICsPtTaskService csPtTaskService;

	@Autowired
	private ICsPtTaskmxService csPtTaskmxService;


	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * @param csPtTask
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "异步任务-分页列表查询")
	@ApiOperation(value="异步任务-分页列表查询", notes="异步任务-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CsPtTask>> queryPageList(CsPtTask csPtTask,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<CsPtTask> queryWrapper = QueryGenerator.initQueryWrapper(csPtTask, req.getParameterMap());
		Page<CsPtTask> page = new Page<CsPtTask>(pageNo, pageSize);
		IPage<CsPtTask> pageList = csPtTaskService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
     *   添加
     * @param csPtTask
     * @return
     */
    @AutoLog(value = "异步任务-添加")
    @ApiOperation(value="异步任务-添加", notes="异步任务-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody CsPtTask csPtTask) {
        csPtTaskService.save(csPtTask);
        return Result.OK("添加成功！");
    }

    /**
     *  编辑
     * @param csPtTask
     * @return
     */
    @AutoLog(value = "异步任务-编辑")
    @ApiOperation(value="异步任务-编辑", notes="异步任务-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result<String> edit(@RequestBody CsPtTask csPtTask) {
        csPtTaskService.updateById(csPtTask);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @AutoLog(value = "异步任务-通过id删除")
    @ApiOperation(value="异步任务-通过id删除", notes="异步任务-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name="id",required=true) String id) {
        csPtTaskService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @AutoLog(value = "异步任务-批量删除")
    @ApiOperation(value="异步任务-批量删除", notes="异步任务-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.csPtTaskService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CsPtTask csPtTask) {
        return super.exportXls(request, csPtTask, CsPtTask.class, "异步任务");
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CsPtTask.class);
    }
	/*---------------------------------主表处理-end-------------------------------------*/
	

    /*--------------------------------子表处理-异步任务明细表-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	//@AutoLog(value = "异步任务明细表-通过主表ID查询")
	@ApiOperation(value="异步任务明细表-通过主表ID查询", notes="异步任务明细表-通过主表ID查询")
	@GetMapping(value = "/listCsPtTaskmxByMainId")
    public Result<IPage<CsPtTaskmx>> listCsPtTaskmxByMainId(CsPtTaskmx csPtTaskmx,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<CsPtTaskmx> queryWrapper = QueryGenerator.initQueryWrapper(csPtTaskmx, req.getParameterMap());
        Page<CsPtTaskmx> page = new Page<CsPtTaskmx>(pageNo, pageSize);
        IPage<CsPtTaskmx> pageList = csPtTaskmxService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param csPtTaskmx
	 * @return
	 */
	@AutoLog(value = "异步任务明细表-添加")
	@ApiOperation(value="异步任务明细表-添加", notes="异步任务明细表-添加")
	@PostMapping(value = "/addCsPtTaskmx")
	public Result<String> addCsPtTaskmx(@RequestBody CsPtTaskmx csPtTaskmx) {
		csPtTaskmxService.save(csPtTaskmx);
		return Result.OK("添加成功！");
	}

    /**
	 * 编辑
	 * @param csPtTaskmx
	 * @return
	 */
	@AutoLog(value = "异步任务明细表-编辑")
	@ApiOperation(value="异步任务明细表-编辑", notes="异步任务明细表-编辑")
	@RequestMapping(value = "/editCsPtTaskmx", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> editCsPtTaskmx(@RequestBody CsPtTaskmx csPtTaskmx) {
		csPtTaskmxService.updateById(csPtTaskmx);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "异步任务明细表-通过id删除")
	@ApiOperation(value="异步任务明细表-通过id删除", notes="异步任务明细表-通过id删除")
	@DeleteMapping(value = "/deleteCsPtTaskmx")
	public Result<String> deleteCsPtTaskmx(@RequestParam(name="id",required=true) String id) {
		csPtTaskmxService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "异步任务明细表-批量删除")
	@ApiOperation(value="异步任务明细表-批量删除", notes="异步任务明细表-批量删除")
	@DeleteMapping(value = "/deleteBatchCsPtTaskmx")
	public Result<String> deleteBatchCsPtTaskmx(@RequestParam(name="ids",required=true) String ids) {
	    this.csPtTaskmxService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportCsPtTaskmx")
    public ModelAndView exportCsPtTaskmx(HttpServletRequest request, CsPtTaskmx csPtTaskmx) {
		 // Step.1 组装查询条件
		 QueryWrapper<CsPtTaskmx> queryWrapper = QueryGenerator.initQueryWrapper(csPtTaskmx, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<CsPtTaskmx> pageList = csPtTaskmxService.list(queryWrapper);
		 List<CsPtTaskmx> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, "异步任务明细表");
		 mv.addObject(NormalExcelConstants.CLASS, CsPtTaskmx.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("异步任务明细表报表", "导出人:" + sysUser.getRealname(), "异步任务明细表"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importCsPtTaskmx/{mainId}")
    public Result<?> importCsPtTaskmx(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
       // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<CsPtTaskmx> list = ExcelImportUtil.importExcel(file.getInputStream(), CsPtTaskmx.class, params);
				 for (CsPtTaskmx temp : list) {
                    temp.setFromid(mainId);
				 }
				 long start = System.currentTimeMillis();
				 csPtTaskmxService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
//					 e.printStackTrace();
					 log.error(e.getMessage(), e);
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-异步任务明细表-end----------------------------------------------*/




}
