package cn.iocoder.yudao.module.pms.controller.admin.iotdevicestatuslog;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.number.NumberUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.pms.controller.admin.iotdevicestatuslog.vo.IotDeviceStatusLogPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotdevicestatuslog.vo.IotDeviceStatusLogRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotdevicestatuslog.vo.IotDeviceStatusLogSaveReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.vo.IotDevicePageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.vo.IotDeviceRespVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotdevicestatuslog.IotDeviceStatusLogDO;
import cn.iocoder.yudao.module.pms.service.IotDeviceService;
import cn.iocoder.yudao.module.pms.service.iotdevicestatuslog.IotDeviceStatusLogService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.dict.DictDataDO;
import cn.iocoder.yudao.module.system.service.dict.DictDataService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;
import java.util.stream.Stream;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertListByFlatMap;

@Tag(name = "管理后台 - 设备状态调整日志")
@RestController
@RequestMapping("/pms/iot-device-status-log")
@Validated
public class IotDeviceStatusLogController {

    @Resource
    private IotDeviceStatusLogService iotDeviceStatusLogService;
    @Resource
    private IotDeviceService iotDeviceService;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private DictDataService dictDataService;

    @PostMapping("/create")
    @Operation(summary = "创建设备状态调整日志")
    @PreAuthorize("@ss.hasPermission('pms:iot-device-status-log:create')")
    public CommonResult<Long> createIotDeviceStatusLog(@Valid @RequestBody IotDeviceStatusLogSaveReqVO createReqVO) {
        return success(iotDeviceStatusLogService.createIotDeviceStatusLog(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新设备状态调整日志")
    @PreAuthorize("@ss.hasPermission('pms:iot-device-status-log:update')")
    public CommonResult<Boolean> updateIotDeviceStatusLog(@Valid @RequestBody IotDeviceStatusLogSaveReqVO updateReqVO) {
        iotDeviceStatusLogService.updateIotDeviceStatusLog(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除设备状态调整日志")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('pms:iot-device-status-log:delete')")
    public CommonResult<Boolean> deleteIotDeviceStatusLog(@RequestParam("id") Long id) {
        iotDeviceStatusLogService.deleteIotDeviceStatusLog(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得设备状态调整日志")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('pms:iot-device-status-log:query')")
    public CommonResult<IotDeviceStatusLogRespVO> getIotDeviceStatusLog(@RequestParam("id") Long id) {
        IotDeviceStatusLogDO iotDeviceStatusLog = iotDeviceStatusLogService.getIotDeviceStatusLog(id);
        return success(BeanUtils.toBean(iotDeviceStatusLog, IotDeviceStatusLogRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得设备状态调整日志分页")
    @PreAuthorize("@ss.hasPermission('pms:iot-device-status-log:query')")
    public CommonResult<PageResult<IotDeviceStatusLogRespVO>> getIotDeviceStatusLogPage(@Valid IotDeviceStatusLogPageReqVO pageReqVO) {
        PageResult<IotDeviceStatusLogDO> pageResult = iotDeviceStatusLogService.getIotDeviceStatusLogPage(pageReqVO);
        // 组装关联的 设备 信息
        return success(new PageResult<>(buildDeviceStatusList(pageResult.getList()), pageResult.getTotal()));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出设备状态调整日志列表 Excel")
    @PreAuthorize("@ss.hasPermission('pms:iot-device-status-log:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotDeviceStatusLogExcel(@Valid IotDeviceStatusLogPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        // 先查询符合条件的设备id集合 再根据deviceIds集合查询对应的调拨记录
        IotDevicePageReqVO deviceReqVO = new IotDevicePageReqVO();
        BeanUtils.copyProperties(pageReqVO, deviceReqVO);
        deviceReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<IotDeviceRespVO> relationDevices = iotDeviceService.statusRelationDevices(deviceReqVO).getList();
        List<Long> deviceIds = new ArrayList<>();

        if (CollUtil.isNotEmpty(relationDevices)) {
            relationDevices.forEach(device -> {
                deviceIds.add(device.getId());
            });
        }
        if (CollUtil.isEmpty(deviceIds)) {
            deviceIds.add(Long.MAX_VALUE);
        }
        pageReqVO.setDeviceIds(deviceIds);
        List<IotDeviceStatusLogDO> list = iotDeviceStatusLogService.getIotDeviceStatusLogPage(pageReqVO).getList();
        List<IotDeviceStatusLogRespVO> deviceStatusLogs = buildDeviceStatusList(list);
        // 查询设备状态字典表
        // key施工状态数据字典value   value施工状态数据字典label
        Map<String, String> deviceStatusPair = new HashMap<>();
        // 施工状态 字典数据
        List<DictDataDO> deviceStatusData = dictDataService.getDictDataListByDictType("pms_device_status");
        if (CollUtil.isNotEmpty(deviceStatusData)) {
            deviceStatusData.forEach(data -> {
                deviceStatusPair.put(data.getValue(), data.getLabel());
            });
        }
        if (CollUtil.isNotEmpty(deviceStatusLogs)) {
            deviceStatusLogs.forEach(log -> {
                // 创建时间 格式化 yyyy-MM-dd
                if (ObjUtil.isNotEmpty(log.getCreateTime())) {
                    log.setCreateTimeStr(LocalDateTimeUtil.format(log.getCreateTime(), DatePattern.NORM_DATETIME_PATTERN));
                }
                // 设备名称 去掉多语言标识
                String deviceName = log.getDeviceName();
                if (StrUtil.isNotBlank(deviceName) && deviceName.contains("~~")) {
                    // 截取首次~~之前的部分
                    String processedName = deviceName.substring(0, deviceName.indexOf("~~"));
                    log.setDeviceName(processedName);
                }
                // 调整前状态 去掉 多语言标识
                if (StrUtil.isNotBlank(log.getOldStatus()) && deviceStatusPair.containsKey(log.getOldStatus())) {
                    String oldStatus = deviceStatusPair.get(log.getOldStatus());
                    if (oldStatus.contains("~~")) {
                        // 截取首次~~之前的部分
                        String processedName = oldStatus.substring(0, oldStatus.indexOf("~~"));
                        log.setOldStatus(processedName);
                    } else {
                        log.setOldStatus(oldStatus);
                    }
                }
                // 调整后状态 去掉 多语言标识
                if (StrUtil.isNotBlank(log.getNewStatus()) && deviceStatusPair.containsKey(log.getNewStatus())) {
                    String newStatus = deviceStatusPair.get(log.getNewStatus());
                    if (newStatus.contains("~~")) {
                        // 截取首次~~之前的部分
                        String processedName = newStatus.substring(0, newStatus.indexOf("~~"));
                        log.setNewStatus(processedName);
                    } else {
                        log.setNewStatus(newStatus);
                    }
                }
            });
        }
        // 导出 Excel
        ExcelUtils.write(response, "设备调拨日志.xls", "设备调拨日志", IotDeviceStatusLogRespVO.class,
                deviceStatusLogs);
    }

    private List<IotDeviceStatusLogRespVO> buildDeviceStatusList(List<IotDeviceStatusLogDO> deviceStatuses) {
        if (CollUtil.isEmpty(deviceStatuses)) {
            return Collections.emptyList();
        }
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(convertListByFlatMap(deviceStatuses,
                status -> Stream.of(NumberUtils.parseLong(status.getCreator()))));
        // 组装bom关联的设备信息
        Map<Long, IotDeviceRespVO> deviceMap = iotDeviceService.getDeviceMap(convertListByFlatMap(deviceStatuses,
                status -> Stream.of(status.getDeviceId())));
        // 2. 转换成 VO
        return BeanUtils.toBean(deviceStatuses, IotDeviceStatusLogRespVO.class, statusVO -> {
            // 设置设备相关信息
            MapUtils.findAndThen(deviceMap, statusVO.getDeviceId(),
                    device -> statusVO.setDeviceName(device.getDeviceName()));
            MapUtils.findAndThen(deviceMap, statusVO.getDeviceId(),
                    device -> statusVO.setDeviceCode(device.getDeviceCode()));
            MapUtils.findAndThen(userMap, NumberUtils.parseLong(statusVO.getCreator()),
                    user -> statusVO.setCreatorName(user.getNickname()));
        });
    }

}