package cn.iocoder.yudao.module.iot.controller.admin.devicemodelattribute;

import cn.iocoder.yudao.module.iot.dal.dataobject.deviceattributetype.DeviceAttributeTypeDO;
import cn.iocoder.yudao.module.iot.dal.mysql.devicemodelattribute.DeviceModelAttributeMapper;
import io.swagger.v3.oas.annotations.Parameters;
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.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.iot.controller.admin.devicemodelattribute.vo.*;
import cn.iocoder.yudao.module.iot.dal.dataobject.devicemodelattribute.DeviceModelAttributeDO;
import cn.iocoder.yudao.module.iot.service.devicemodelattribute.DeviceModelAttributeService;
import org.springframework.web.multipart.MultipartFile;

@Tag(name = "管理后台 - 采集设备模型-点位管理")
@RestController
@RequestMapping("/iot/device-model-attribute")
@Validated
public class DeviceModelAttributeController {

    @Resource
    private DeviceModelAttributeService deviceModelAttributeService;
    @Resource
    private DeviceModelAttributeMapper deviceModelAttributeMapper;

    @PostMapping("/create")
    @Operation(summary = "创建采集设备模型-点位管理")
    @PreAuthorize("@ss.hasPermission('iot:device-model-attribute:create')")
    public CommonResult<Long> createDeviceModelAttribute(@Valid @RequestBody DeviceModelAttributeSaveReqVO createReqVO) {
        return success(deviceModelAttributeService.createDeviceModelAttribute(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新采集设备模型-点位管理")
    @PreAuthorize("@ss.hasPermission('iot:device-model-attribute:update')")
    public CommonResult<Boolean> updateDeviceModelAttribute(@Valid @RequestBody DeviceModelAttributeSaveReqVO updateReqVO) {
        deviceModelAttributeService.updateDeviceModelAttribute(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除采集设备模型-点位管理")
    @Parameter(name = "ids", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('iot:device-model-attribute:delete')")
    public CommonResult<Boolean> deleteDeviceModelAttribute(@RequestParam("ids") String ids) {
        // 将逗号分隔的字符串转换为Long类型的List
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(String::trim) // 去除可能存在的空格
                .map(Long::valueOf)
                .collect(Collectors.toList());
        deviceModelAttributeService.deleteDeviceModelAttribute(idList);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得采集设备模型-点位管理")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('iot:device-model-attribute:query')")
    public CommonResult<DeviceModelAttributeRespVO> getDeviceModelAttribute(@RequestParam("id") Long id) {
        DeviceModelAttributeDO deviceModelAttribute = deviceModelAttributeService.getDeviceModelAttribute(id);
        return success(BeanUtils.toBean(deviceModelAttribute, DeviceModelAttributeRespVO.class));
    }

    @GetMapping("/list")
    @Operation(summary = "获得采集设备模型-点位管理 列表")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('iot:device-model-attribute:query')")
    public CommonResult<List<DeviceModelAttributeDO>> getDeviceModelAttributeList(@RequestParam("id") Long id) {
        List<DeviceModelAttributeDO> deviceModelAttribute = deviceModelAttributeService.getDeviceModelAttributeList(id);
        return success(deviceModelAttribute);
    }


    @GetMapping("/page")
    @Operation(summary = "获得采集设备模型-点位管理分页")
    @PreAuthorize("@ss.hasPermission('iot:device-model-attribute:query')")
    public CommonResult<PageResult<DeviceModelAttributeRespVO>> getDeviceModelAttributePage(@Valid DeviceModelAttributePageReqVO pageReqVO) {
        PageResult<DeviceModelAttributeRespVO> pageResult = deviceModelAttributeService.getDeviceModelAttributePage(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出采集设备模型-点位管理 Excel")
    @PreAuthorize("@ss.hasPermission('iot:device-model-attribute:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDeviceModelAttributeExcel(@Valid DeviceModelAttributePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<DeviceModelAttributeRespVO> list = deviceModelAttributeService.getDeviceModelAttributePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "采集设备模型-点位管理.xls", "数据", DeviceModelAttributeRespVO.class,list);
    }


    @GetMapping("/operationAnalysisDetails")
    @Operation(summary = "设备运行参数分析-详情")
//    @Parameter(name = "deviceId,modelId", description = "设备id，点位参数id", required = true)
    @PreAuthorize("@ss.hasPermission('iot:device-model-attribute:query')")
    public CommonResult<List<Map<String, Object>>> operationAnalysisDetails(@RequestParam("deviceId") Long deviceId,
                                                                             @RequestParam("modelId") Long modelId,
                                                                             @RequestParam(name = "collectionStartTime", required = false ) String collectionStartTime,
                                                                             @RequestParam(name = "collectionEndTime", required = false ) String collectionEndTime) {
        List<Map<String, Object>> deviceModelAttribute = deviceModelAttributeService.operationAnalysisDetails(deviceId,modelId,collectionStartTime,collectionEndTime);
        return success(deviceModelAttribute);
    }

    ///////////////  以下是新增的代码 ///////////////
    @GetMapping("/get-import-template")
    @Operation(summary = "获取采集设备模型-点位管理导入模板")
    @PreAuthorize("@ss.hasPermission('iot:device-model-attribute:import')")
    @ApiAccessLog(operateType = EXPORT)
    public void getImportTemplate(HttpServletResponse response) throws IOException {
        // 准备模板数据
        List<DeviceModelAttributeImportExcelVO> list = new ArrayList<>();
        list.add(DeviceModelAttributeImportExcelVO.builder()
                .attributeCode("test")
                .attributeName("温度")
//                .attributeType("1")
                .typeName("报警信息")
                .dataType("int64")
                .address("AI0")
                .dataUnit("s")
                .ratio(1.0)
                .remark("温度传感器")
                .build());
        list.add(DeviceModelAttributeImportExcelVO.builder()
                .attributeCode("humidity_001")
                .attributeName("湿度")
//                .attributeType("2")
                .typeName("能源参数")
                .dataType("int64")
                .address("AI1")
                .dataUnit("s")
                .ratio(1.0)
                .remark("湿度传感器")
                .build());
        // 输出
        ExcelUtils.write(response, "采集设备模型-点位管理导入模板.xls", "数据", DeviceModelAttributeImportExcelVO.class, list);
    }


    @PostMapping("/import")
    @Operation(summary = "导入设备采集点位") // 对应 User 的 "导入用户"
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "deviceModelId", description = "设备型号ID", required = true, example = "1024"),
            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
    }) // 完全复用你的 Parameters 注解格式
    @PreAuthorize("@ss.hasPermission('system:device-model-attribute:import')") // 对齐 User 的权限码风格
    public CommonResult<DeviceModelAttributeImportRespVO> importExcel(
            @RequestParam("file") MultipartFile file,
            @RequestParam("deviceModelId") Long deviceModelId,
            @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        // 1. 读取 Excel 数据 - 完全复用你的 ExcelUtils.read 调用方式
        List<DeviceModelAttributeImportExcelVO> list = ExcelUtils.read(file, DeviceModelAttributeImportExcelVO.class);
        // 2. 调用 Service 并返回结果 - 完全复用你的 success 包装方式
        return success(deviceModelAttributeService.importAttributeList(list, deviceModelId, updateSupport));
    }


}