package cn.iocoder.yudao.module.mes.controller.admin.devicetype;

import cn.iocoder.yudao.module.mes.controller.admin.devicetype.vo.DeviceTypeTreeRespVO;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.mes.controller.admin.devicetype.vo.*;
import cn.iocoder.yudao.module.mes.dal.dataobject.devicetype.DeviceTypeDO;
import cn.iocoder.yudao.module.mes.service.devicetype.DeviceTypeService;

@Tag(name = "管理后台 - 设备类型")
@RestController
@RequestMapping("/mes/device-type")
@Validated
public class DeviceTypeController {

    @Resource
    private DeviceTypeService deviceTypeService;

    @PostMapping("/create")
    @Operation(summary = "创建设备类型")
    @PreAuthorize("@ss.hasPermission('mes:device-type:create')")
    public CommonResult<Long> createDeviceType(@Valid @RequestBody DeviceTypeSaveReqVO createReqVO) {
        return success(deviceTypeService.createDeviceType(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新设备类型")
    @PreAuthorize("@ss.hasPermission('mes:device-type:update')")
    public CommonResult<Boolean> updateDeviceType(@Valid @RequestBody DeviceTypeSaveReqVO updateReqVO) {
        deviceTypeService.updateDeviceType(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除设备类型")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:device-type:delete')")
    public CommonResult<Boolean> deleteDeviceType(@RequestParam("id") Long id) {
        deviceTypeService.deleteDeviceType(id);
        return success(true);
    }

    @DeleteMapping("/delete-batch")
    @Operation(summary = "批量删除设备类型")
    @PreAuthorize("@ss.hasPermission('mes:device-type:delete')")
    public CommonResult<Boolean> deleteDeviceTypeBatch(@RequestParam("ids") List<Long> ids) {
        deviceTypeService.deleteDeviceTypeBatch(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得设备类型")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:device-type:query')")
    public CommonResult<DeviceTypeRespVO> getDeviceType(@RequestParam("id") Long id) {
        DeviceTypeDO deviceType = deviceTypeService.getDeviceType(id);
        return success(BeanUtils.toBean(deviceType, DeviceTypeRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得设备类型分页")
    @PreAuthorize("@ss.hasPermission('mes:device-type:query')")
    public CommonResult<PageResult<DeviceTypeRespVO>> getDeviceTypePage(@Valid DeviceTypePageReqVO pageReqVO) {
        PageResult<DeviceTypeDO> pageResult = deviceTypeService.getDeviceTypePage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, DeviceTypeRespVO.class));
    }

    @GetMapping("/list")
    @Operation(summary = "获得设备类型列表")
    @PreAuthorize("@ss.hasPermission('mes:device-type:query')")
    public CommonResult<List<DeviceTypeRespVO>> getDeviceTypeList(@Valid DeviceTypeListReqVO listReqVO) {
        List<DeviceTypeDO> list = deviceTypeService.getDeviceTypeList(listReqVO);
        return success(BeanUtils.toBean(list, DeviceTypeRespVO.class));
    }

    @GetMapping("/tree")
    @Operation(summary = "获得设备类型树")
    @PreAuthorize("@ss.hasPermission('mes:device-type:query')")
    public CommonResult<List<DeviceTypeTreeRespVO>> getDeviceTypeTree(@Valid DeviceTypeListReqVO pageReqVO) {
        List<DeviceTypeTreeRespVO> tree = deviceTypeService.getDeviceTypeTree(pageReqVO);
        return success(tree);
    }

    @GetMapping("/children")
    @Operation(summary = "获得子设备类型列表")
    @Parameter(name = "parentId", description = "父级ID", required = true, example = "0")
    @PreAuthorize("@ss.hasPermission('mes:device-type:query')")
    public CommonResult<List<DeviceTypeRespVO>> getChildrenDeviceTypes(@RequestParam("parentId") Long parentId) {
        List<DeviceTypeDO> list = deviceTypeService.getChildrenDeviceTypes(parentId);
        return success(BeanUtils.toBean(list, DeviceTypeRespVO.class));
    }

    @GetMapping("/ancestors")
    @Operation(summary = "获得祖先设备类型列表")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:device-type:query')")
    public CommonResult<List<DeviceTypeRespVO>> getAncestorDeviceTypes(@RequestParam("id") Long id) {
        List<DeviceTypeDO> list = deviceTypeService.getAncestorDeviceTypes(id);
        return success(BeanUtils.toBean(list, DeviceTypeRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出设备类型 Excel")
    @PreAuthorize("@ss.hasPermission('mes:device-type:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDeviceTypeExcel(@Valid DeviceTypeListReqVO pageReqVO,
                                      HttpServletResponse response) throws IOException {

        List<DeviceTypeDO> deviceTypeList = deviceTypeService.getDeviceTypeList(pageReqVO);
        List<DeviceTypeRespVO> deviceTypeRespVOList = BeanUtils.toBean(deviceTypeList, DeviceTypeRespVO.class);
        // 创建ID到名称的映射
        Map<Long, String> idToNameMap = deviceTypeList.stream()
                .collect(Collectors.toMap(
                        DeviceTypeDO::getId,
                        DeviceTypeDO::getName,
                        (v1, v2) -> v1
                ));

        // 设置父类名称
        for (DeviceTypeRespVO deviceTypeRespVO : deviceTypeRespVOList) {
            if (deviceTypeRespVO.getParentId() != null && deviceTypeRespVO.getParentId() > 0) {
                // 从映射中获取父类名称
                deviceTypeRespVO.setParentName(idToNameMap.getOrDefault(deviceTypeRespVO.getParentId(), ""));
            } else {
                deviceTypeRespVO.setParentName("顶级分类");
            }
        }


        // 设置响应头
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode("维修记录.xls", "UTF-8"));
        response.setHeader("Content-Encoding", "identity");
        // 导出Excel
        String fileName = String.format("维修记录_%s.xls", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        // 导出 Excel
        ExcelUtils.write(response, fileName, "数据", DeviceTypeRespVO.class,deviceTypeRespVOList);
    }
}