package org.jeecg.modules.device.controller;

import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.device.entity.DeviceBreakdownReport;
import org.jeecg.modules.device.service.IDeviceBreakdownReportService;

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.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.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 设备故障报修
 * @Author: jeecg-boot
 * @Date:   2025-03-03
 * @Version: V1.0
 */
@Api(tags="设备故障报修")
@RestController
@RequestMapping("/device/deviceBreakdownReport")
@Slf4j
public class DeviceBreakdownReportController extends JeecgController<DeviceBreakdownReport, IDeviceBreakdownReportService> {
	@Autowired
	private IDeviceBreakdownReportService deviceBreakdownReportService;
	@Value("${jeecg.path.upload}")
	private String upLoadPath;

	/**
	 * 分页列表查询
	 *
	 * @param deviceBreakdownReport
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "设备故障报修-分页列表查询")
	@ApiOperation(value="设备故障报修-分页列表查询", notes="设备故障报修-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<DeviceBreakdownReport>> queryPageList(DeviceBreakdownReport deviceBreakdownReport,
															  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
															  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
															  HttpServletRequest req) {
		QueryWrapper<DeviceBreakdownReport> queryWrapper = QueryGenerator.initQueryWrapper(deviceBreakdownReport, req.getParameterMap());
		queryWrapper.eq("delete_flag",0);
		Page<DeviceBreakdownReport> page = new Page<DeviceBreakdownReport>(pageNo, pageSize);
		IPage<DeviceBreakdownReport> pageList = deviceBreakdownReportService.page(page, queryWrapper);
		pageList.getRecords().forEach(item->{
			item.setDevice1Id(item.getDeviceId());
		});
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param deviceBreakdownReport
	 * @return
	 */
	@AutoLog(value = "设备故障报修-添加")
	@ApiOperation(value="设备故障报修-添加", notes="设备故障报修-添加")
	//@RequiresPermissions("org.jeecg.modules:bu_device_breakdown_report:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody DeviceBreakdownReport deviceBreakdownReport) {
		deviceBreakdownReportService.save(deviceBreakdownReport);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param deviceBreakdownReport
	 * @return
	 */
	@AutoLog(value = "设备故障报修-编辑")
	@ApiOperation(value="设备故障报修-编辑", notes="设备故障报修-编辑")
	//@RequiresPermissions("org.jeecg.modules:bu_device_breakdown_report:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody DeviceBreakdownReport deviceBreakdownReport) {
		//获取登录用户信息
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		deviceBreakdownReport.setAduitBy(sysUser.getId());
		deviceBreakdownReportService.updateById(deviceBreakdownReport);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "设备故障报修-通过id删除")
	@ApiOperation(value="设备故障报修-通过id删除", notes="设备故障报修-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:bu_device_breakdown_report:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		deviceBreakdownReportService.update(null,new LambdaUpdateWrapper<DeviceBreakdownReport>().set(DeviceBreakdownReport::getDeleteFlag,1)
				.eq(DeviceBreakdownReport::getId,id));
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "设备故障报修-批量删除")
	@ApiOperation(value="设备故障报修-批量删除", notes="设备故障报修-批量删除")
	//@RequiresPermissions("org.jeecg.modules:bu_device_breakdown_report:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.deviceBreakdownReportService.update(null,new LambdaUpdateWrapper<DeviceBreakdownReport>().set(DeviceBreakdownReport::getDeleteFlag,1)
				.in(DeviceBreakdownReport::getId,Arrays.asList(ids.split(","))));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "设备故障报修-通过id查询")
	@ApiOperation(value="设备故障报修-通过id查询", notes="设备故障报修-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<DeviceBreakdownReport> queryById(@RequestParam(name="id",required=true) String id) {
		DeviceBreakdownReport deviceBreakdownReport = deviceBreakdownReportService.getById(id);
		if(deviceBreakdownReport==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(deviceBreakdownReport);
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param deviceBreakdownReport
	 */
	//@RequiresPermissions("org.jeecg.modules:bu_device_breakdown_report:exportXls")
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, DeviceBreakdownReport deviceBreakdownReport) {
		// Step.1 组装查询条件
		QueryWrapper<DeviceBreakdownReport> queryWrapper = QueryGenerator.initQueryWrapper(deviceBreakdownReport, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		// 过滤选中数据
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			queryWrapper.in("id",selectionList);
		}
		// Step.2 获取导出数据
		List<DeviceBreakdownReport> exportList = service.list(queryWrapper);
		exportList.forEach(item->{
			item.setDevice1Id(item.getDeviceId());
		});

		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		//此处设置的filename无效 ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.FILE_NAME, "设备故障报修");
		mv.addObject(NormalExcelConstants.CLASS, DeviceBreakdownReport.class);
		//update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
		ExportParams exportParams=new ExportParams("设备故障报修报表", "导出人:" + sysUser.getRealname(), "设备故障报修");
		exportParams.setImageBasePath(upLoadPath);
		//update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
		mv.addObject(NormalExcelConstants.PARAMS,exportParams);
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	//@RequiresPermissions("bu_device_breakdown_report:importExcel")
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("file");
		if (file == null || file.isEmpty()) {
			return Result.error("文件为空");
		}

		ImportParams params = new ImportParams();
		params.setTitleRows(1); // 第2行为表头
		params.setHeadRows(1);  // 跳过第1行
		params.setStartRows(1); // 数据从第4行开始（索引=2）

		try {
			List<DeviceBreakdownReport> list = ExcelImportUtil.importExcel(
					file.getInputStream(),
					DeviceBreakdownReport.class,
					params
			);

			// 过滤全空行
			list.removeIf(r ->
					r.getCreateTime() == null ||
							StringUtils.isBlank(r.getCreateBy()) ||
							StringUtils.isBlank(r.getDescription())
			);

			// 调用 Service 进行后处理与保存
			deviceBreakdownReportService.saveBatchFromExcel(list);

			return Result.ok("成功导入 " + list.size() + " 条记录");
		} catch (Exception e) {
			log.error("Excel导入失败", e);
			return Result.error("导入失败：" + e.getMessage());
		}
	}

	@ApiOperation(value="设备故障报修-申请审批", notes="设备故障报修-申请审批")
	@PostMapping(value = "/aduit")
	public Result<?> aduit(@RequestBody DeviceBreakdownReport data){
		if(deviceBreakdownReportService.aduit(data)){
			return Result.OK();
		}else{
			return Result.error("审批失败");
		}
	}

}
