package org.jeecg.modules.device.controller;

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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.device.entity.BuDevice;
import org.jeecg.modules.device.entity.BuDeviceType;
import org.jeecg.modules.device.mapper.BuDeviceMapper;
import org.jeecg.modules.device.service.IBuDeviceTypeService;
import org.springframework.beans.factory.annotation.Autowired;
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:   2024-04-25
 * @Version: V1.0
 */
@Api(tags="设备类型")
@RestController
@RequestMapping("/device/buDeviceType")
@Slf4j
public class BuDeviceTypeController extends JeecgController<BuDeviceType, IBuDeviceTypeService> {
	@Autowired
	private BuDeviceMapper deviceMapper;
	@Autowired
	private IBuDeviceTypeService buDeviceTypeService;

	/**
	 * 分页列表查询
	 *
	 * @param buDeviceType
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "设备类型-分页列表查询")
	@ApiOperation(value="设备类型-分页列表查询", notes="设备类型-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BuDeviceType>> queryPageList(BuDeviceType buDeviceType,
													 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													 HttpServletRequest req) {
//		QueryWrapper<BuDeviceType> queryWrapper = QueryGenerator.initQueryWrapper(buDeviceType, req.getParameterMap());
		LambdaQueryWrapper<BuDeviceType> queryWrapper = new LambdaQueryWrapper<BuDeviceType>()
				.isNull(BuDeviceType::getPid)
				.like(StringUtils.isNotBlank(buDeviceType.getTypeName()),BuDeviceType::getTypeName,buDeviceType.getTypeName())
				.like(StringUtils.isNotBlank(buDeviceType.getTypeCode()),BuDeviceType::getTypeCode,buDeviceType.getTypeCode());
		Page<BuDeviceType> page = new Page<BuDeviceType>(pageNo, pageSize);
		IPage<BuDeviceType> pageList = buDeviceTypeService.page(page, queryWrapper);
		pageList.setRecords(buDeviceTypeService.buildTree(pageList.getRecords()));
		return Result.OK(pageList);
	}

	/**
	 * 获取全部类型
	 * @param buDeviceType
	 * @return
	 */
	 @GetMapping(value = "/list/all")
	 @ApiOperation(value="设备类型-通过calss区分设备还是部件", notes="设备类型-通过calss区分设备还是部件")
	 public Result<List<BuDeviceType>> queryAllList(BuDeviceType buDeviceType) {
		 LambdaQueryWrapper<BuDeviceType> wrapper = new LambdaQueryWrapper<>();
		 wrapper.eq(StringUtils.isNotBlank(buDeviceType.getCalss()), BuDeviceType::getCalss, buDeviceType.getCalss())
				 .eq(StringUtils.isNotBlank(buDeviceType.getPid()), BuDeviceType::getPid, buDeviceType.getPid());
		 // 如果传了 deviceId，则关联设备表获取 deviceTypeId 作为 pid 查询条件
		 String deviceId = buDeviceType.getDeviceId();
		 if (deviceId != null) {
			 BuDevice device = deviceMapper.selectById(deviceId);
			 if (device != null && device.getDeviceTypeId() != null) {
				 wrapper.eq(BuDeviceType::getPid, device.getDeviceTypeId());
			 }
		 }
		 // 查询数据
		 List<BuDeviceType> list = buDeviceTypeService.list(wrapper);

		 return Result.ok(buDeviceTypeService.buildTree(list));
	 }

	@GetMapping(value = "/list/deviceType")
	public Result<List<BuDeviceType>> queryAlldeviceType() {
		List<BuDeviceType> pageList = buDeviceTypeService.list(new LambdaQueryWrapper<BuDeviceType>().eq(BuDeviceType::getCalss,1));
		// 优化 HashMap 初始容量，减少扩容开销
		Map<String, BuDeviceType> typeMap = new HashMap<>(pageList.size());
		// 使用 forEach 填充 Map，代码更简洁
		pageList.forEach(type -> typeMap.put(type.getId(), type));

		List<BuDeviceType> rootList = new ArrayList<>();
		for (BuDeviceType type : pageList) {
			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);
	}

	/**
	 *   添加
	 *
	 * @param buDeviceType
	 * @return
	 */
	@AutoLog(value = "设备类型-添加")
	@ApiOperation(value="设备类型-添加", notes="设备类型-添加")
	//@RequiresPermissions("org.jeecg.modules.demo:bu_device_type:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BuDeviceType buDeviceType) {
		buDeviceTypeService.save(buDeviceType);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param buDeviceType
	 * @return
	 */
	@AutoLog(value = "设备类型-编辑")
	@ApiOperation(value="设备类型-编辑", notes="设备类型-编辑")
	//@RequiresPermissions("org.jeecg.modules.demo:bu_device_type:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BuDeviceType buDeviceType) {
		buDeviceTypeService.updateById(buDeviceType);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "设备类型-通过id删除")
	@ApiOperation(value="设备类型-通过id删除", notes="设备类型-通过id删除")
	//@RequiresPermissions("org.jeecg.modules.demo:bu_device_type:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		buDeviceTypeService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "设备类型-批量删除")
	@ApiOperation(value="设备类型-批量删除", notes="设备类型-批量删除")
	//@RequiresPermissions("org.jeecg.modules.demo:bu_device_type:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.buDeviceTypeService.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<BuDeviceType> queryById(@RequestParam(name="id",required=true) String id) {
		BuDeviceType buDeviceType = buDeviceTypeService.getById(id);
		if(buDeviceType==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(buDeviceType);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param buDeviceType
    */
    //@RequiresPermissions("org.jeecg.modules.demo:bu_device_type:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BuDeviceType buDeviceType) {
        return super.exportXls(request, buDeviceType, BuDeviceType.class, "设备类型");
    }

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

}
