package org.jeecg.modules.regular.controller;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.device.entity.BuDeviceType;
import org.jeecg.modules.device.mapper.BuDeviceTypeMapper;
import org.jeecg.modules.device.service.IBuDeviceTypeService;
import org.jeecg.modules.material.entity.BuMaterialInfo;
import org.jeecg.modules.material.service.IBuMaterialInfoService;
import org.jeecg.modules.regular.entity.*;
import org.jeecg.modules.regular.service.IRegularDetailService;
import org.jeecg.modules.regular.service.IRegularMaterialService;
import org.jeecg.modules.regular.service.IRegularService;

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.modules.regular.service.IRegularToolsService;
import org.jeecg.modules.tool.entity.Tool;
import org.jeecg.modules.tool.service.IToolService;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.web.bind.annotation.*;
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-01-16
 * @Version: V1.0
 */
@Api(tags="检修规程")
@RestController
@RequestMapping("/regular/regular")
@Slf4j
@RequiredArgsConstructor
public class RegularController extends JeecgController<Regular, IRegularService> {
	private final IRegularService regularService;
	private final IRegularMaterialService regularMaterialService;
	private final IRegularToolsService regularToolsService;
	private final IRegularDetailService regularDetailService;
	private final IToolService toolService;
	private final IBuMaterialInfoService materialInfoService;
	private final IBuDeviceTypeService buDeviceTypeService;
	/**
	 * 分页列表查询
	 *
	 * @param regular
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "检修规程-分页列表查询")
	@ApiOperation(value="检修规程-分页列表查询", notes="检修规程-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<Regular>> queryPageList(Regular regular,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<Regular> queryWrapper = QueryGenerator.initQueryWrapper(regular, req.getParameterMap());
		Page<Regular> page = new Page<Regular>(pageNo, pageSize);
		IPage<Regular> pageList = regularService.page(page, queryWrapper);
		pageList.getRecords().forEach(item -> {
			List<RegularTools> tools = regularToolsService.list(new LambdaQueryWrapper<RegularTools>()
					.eq(RegularTools::getRegular, item.getId()));
			item.setTools(tools.stream().map(tool ->{
				Tool _temp = toolService.getById(tool.getToolId());
				BaseItem baseItem = new BaseItem();
				baseItem.setName(_temp.getName());
				baseItem.setCount(tool.getCount().toString());
				baseItem.setSpecification(tool.getSpecification());
				baseItem.setUnit(tool.getUnit());
				baseItem.setId(tool.getToolId());
				return baseItem;
			}).collect(Collectors.toList()));

			List<RegularMaterial> materials = regularMaterialService.list(new LambdaQueryWrapper<RegularMaterial>().eq(RegularMaterial::getRegular, item.getId()));
			item.setMaterials(materials.stream().map(material -> {
				BuMaterialInfo materialInfo = materialInfoService.getById(material.getMaterialId());
				BaseItem baseItem = new BaseItem();
				baseItem.setName(materialInfo.getName());
				baseItem.setCount(material.getCount().toString());
				baseItem.setSpecification(material.getSpecification());
				baseItem.setUnit(material.getUnit());
				baseItem.setId(material.getMaterialId());
				return baseItem;
			}).collect(Collectors.toList()));

			List<RegularDetail> regularDetails = regularDetailService.list(new LambdaQueryWrapper<RegularDetail>().eq(RegularDetail::getRegularId,item.getId()).orderByAsc(RegularDetail::getDispOrder));
			item.setRegularDetailList(regularDetails);
		});
		return Result.OK(pageList);
	}

	 @ApiOperation(value="检修规程-列表查询", notes="检修规程-列表查询")
	 @GetMapping(value = "/simplelist")
	 public Result<List<Regular>> queryPageList(Regular regular,HttpServletRequest req) {
		 QueryWrapper<Regular> queryWrapper = QueryGenerator.initQueryWrapper(regular, req.getParameterMap());
		 List<Regular> pageList = regularService.list(queryWrapper);
		 return Result.OK(pageList);
	 }

	/**
	 *   添加
	 *
	 * @param regular
	 * @return
	 */
	@AutoLog(value = "检修规程-添加")
	@ApiOperation(value="检修规程-添加", notes="检修规程-添加")
	//@RequiresPermissions("org.jeecg.modules:bu_regular:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody Regular regular) {
		regularService.save(regular);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param regular
	 * @return
	 */
	@AutoLog(value = "检修规程-编辑")
	@ApiOperation(value="检修规程-编辑", notes="检修规程-编辑")
	//@RequiresPermissions("org.jeecg.modules:bu_regular:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody Regular regular) {
		regularService.updateById(regular);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "检修规程-通过id删除")
	@ApiOperation(value="检修规程-通过id删除", notes="检修规程-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:bu_regular:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		regularService.deleteById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "检修规程-批量删除")
	@ApiOperation(value="检修规程-批量删除", notes="检修规程-批量删除")
	//@RequiresPermissions("org.jeecg.modules:bu_regular:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.regularService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "检修规程-通过id查询")
	@ApiOperation(value="检修规程-通过id查询", notes="检修规程-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<Regular> queryById(@RequestParam(name="id",required=true) String id) {
		Regular regular = regularService.getById(id);
		if(regular==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(regular);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param regular
    */
    //@RequiresPermissions("org.jeecg.modules:bu_regular:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Regular regular) {
        return super.exportXls(request, regular, Regular.class, "检修规程");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("bu_regular:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Regular.class);
    }

	@ApiOperation(value = "获取修程字典列表", notes = "获取修程字典列表")
	@GetMapping("/querymap")
	public Result<?> querymap() {
		return Result.OK(regularService.queryRegularMap());
	}

	@GetMapping("/deviceTypeTree")
	 public Result<List<BuDeviceType>> getDeviceTypeTree() {
		List<Regular> regularList = regularService.list();
		if (regularList.isEmpty())
			return null;
		List<BuDeviceType> deviceTypes = buDeviceTypeService.list(new LambdaQueryWrapper<BuDeviceType>().eq(BuDeviceType::getCalss,1).or()
				.in(BuDeviceType::getId,regularList.stream().map(Regular::getDeviceTypeId).collect(Collectors.toSet())));

		if(deviceTypes.isEmpty())
			return null;

		// 优化 HashMap 初始容量，减少扩容开销
        Map<String, BuDeviceType> typeMap = new HashMap<>(deviceTypes.size());
        // 使用 forEach 填充 Map，代码更简洁
        deviceTypes.forEach(type -> typeMap.put(type.getId(), type));

        List<BuDeviceType> rootList = new ArrayList<>();
        for (BuDeviceType type : deviceTypes) {
            String pid = type.getPid();
            if (pid == null || pid.trim().isEmpty()) {
                rootList.add(type);
            } else {
                BuDeviceType parent = typeMap.get(pid);
                if (parent != null) {
                    // 使用 computeIfAbsent 简化子列表初始化
                    parent.setSubTypes(
                            Optional.ofNullable(parent.getSubTypes()).orElseGet(ArrayList::new)
                    );
                    parent.getSubTypes().add(type);
                }
            }
        }

		return Result.ok(rootList);
	}
}
