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

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.iotdevicepersonlog.vo.IotDevicePersonLogPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotdevicepersonlog.vo.IotDevicePersonLogRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotdevicepersonlog.vo.IotDevicePersonLogSaveReqVO;
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.iotdevicepersonlog.IotDevicePersonLogDO;
import cn.iocoder.yudao.module.pms.service.IotDeviceService;
import cn.iocoder.yudao.module.pms.service.iotdevicepersonlog.IotDevicePersonLogService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
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.Collectors;
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-person-log")
@Validated
public class IotDevicePersonLogController {

    @Resource
    private IotDevicePersonLogService iotDevicePersonLogService;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private IotDeviceService iotDeviceService;

    @PostMapping("/create")
    @Operation(summary = "创建设备责任人日志")
    @PreAuthorize("@ss.hasPermission('pms:iot-device-person-log:create')")
    public CommonResult<Long> createIotDevicePersonLog(@Valid @RequestBody IotDevicePersonLogSaveReqVO createReqVO) {
        return success(iotDevicePersonLogService.createIotDevicePersonLog(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新设备责任人日志")
    @PreAuthorize("@ss.hasPermission('pms:iot-device-person-log:update')")
    public CommonResult<Boolean> updateIotDevicePersonLog(@Valid @RequestBody IotDevicePersonLogSaveReqVO updateReqVO) {
        iotDevicePersonLogService.updateIotDevicePersonLog(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除设备责任人日志")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('pms:iot-device-person-log:delete')")
    public CommonResult<Boolean> deleteIotDevicePersonLog(@RequestParam("id") Long id) {
        iotDevicePersonLogService.deleteIotDevicePersonLog(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得设备责任人日志")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('pms:iot-device-person-log:query')")
    public CommonResult<IotDevicePersonLogRespVO> getIotDevicePersonLog(@RequestParam("id") Long id) {
        IotDevicePersonLogDO iotDevicePersonLog = iotDevicePersonLogService.getIotDevicePersonLog(id);
        return success(BeanUtils.toBean(iotDevicePersonLog, IotDevicePersonLogRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得设备责任人操作日志分页")
    @PreAuthorize("@ss.hasPermission('pms:iot-device-person-log:query')")
    public CommonResult<PageResult<IotDevicePersonLogRespVO>> getIotDevicePersonLogPage(@Valid IotDevicePersonLogPageReqVO pageReqVO) {
        PageResult<IotDevicePersonLogDO> pageResult = iotDevicePersonLogService.getIotDevicePersonLogPage(pageReqVO);
        return success(new PageResult<>(buildDevicePersonList(pageResult.getList()), pageResult.getTotal()));
    }

    private List<IotDevicePersonLogRespVO> buildDevicePersonList(List<IotDevicePersonLogDO> devicePersons) {
        if (CollUtil.isEmpty(devicePersons)) {
            return Collections.emptyList();
        }
        // 修改前责任人 修改后责任人
        List<Long> allPersonIds = devicePersons.stream()
                .flatMap(log -> Stream.of(
                        StrUtil.isNotBlank(log.getOldPersonIds()) ? log.getOldPersonIds().split(",") : new String[0],
                        StrUtil.isNotBlank(log.getNewPersonIds()) ? log.getNewPersonIds().split(",") : new String[0]
                ))
                .flatMap(Arrays::stream)
                .filter(id -> !id.isEmpty())
                .map(String::trim)
                .map(Long::parseLong)
                .collect(Collectors.toList());
        // 查询所有设备责任人姓名(修改前+修改后)
        Map<Long, AdminUserRespDTO> personMap = adminUserApi.getUserMap(allPersonIds);
        // 操作人
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(convertListByFlatMap(devicePersons,
                status -> Stream.of(NumberUtils.parseLong(status.getCreator()))));
        // 组装bom关联的设备信息
        Map<Long, IotDeviceRespVO> deviceMap = iotDeviceService.getDeviceMap(convertListByFlatMap(devicePersons,
                status -> Stream.of(status.getDeviceId())));
        // 2. 转换成 VO
        return BeanUtils.toBean(devicePersons, IotDevicePersonLogRespVO.class, personVO -> {
            // 设置设备相关信息
            MapUtils.findAndThen(deviceMap, personVO.getDeviceId(),
                    device -> personVO.setDeviceName(device.getDeviceName()));
            MapUtils.findAndThen(deviceMap, personVO.getDeviceId(),
                    device -> personVO.setDeviceCode(device.getDeviceCode()));
            MapUtils.findAndThen(userMap, NumberUtils.parseLong(personVO.getCreator()),
                    user -> personVO.setCreatorName(user.getNickname()));
            // 处理oldPersonNames
            if (StrUtil.isNotBlank(personVO.getOldPersonIds())) {
                String oldNames = Arrays.stream(personVO.getOldPersonIds().split(","))
                        .map(String::trim)
                        .map(id -> {
                            try {
                                long personId = Long.parseLong(id);
                                AdminUserRespDTO user = personMap.get(personId);
                                return user != null ? user.getNickname() : null;
                            } catch (NumberFormatException e) {
                                return null;
                            }
                        })
                        .filter(Objects::nonNull)
                        .collect(Collectors.joining(","));
                personVO.setOldPersonNames(oldNames);
            }
            // 处理newPersonNames
            if (StrUtil.isNotBlank(personVO.getNewPersonIds())) {
                String newNames = Arrays.stream(personVO.getNewPersonIds().split(","))
                        .map(String::trim)
                        .map(id -> {
                            try {
                                long personId = Long.parseLong(id);
                                AdminUserRespDTO user = personMap.get(personId);
                                return user != null ? user.getNickname() : null;
                            } catch (NumberFormatException e) {
                                return null;
                            }
                        })
                        .filter(Objects::nonNull)
                        .collect(Collectors.joining(","));
                personVO.setNewPersonNames(newNames);
            }
        });
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出设备责任人日志 Excel")
    @PreAuthorize("@ss.hasPermission('pms:iot-device-person-log:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotDevicePersonLogExcel(@Valid IotDevicePersonLogPageReqVO 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<IotDevicePersonLogDO> list = iotDevicePersonLogService.getIotDevicePersonLogPage(pageReqVO).getList();
        List<IotDevicePersonLogRespVO> devicePersonLogs = buildDevicePersonList(list);
        if (CollUtil.isNotEmpty(devicePersonLogs)) {
            devicePersonLogs.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);
                }
            });
        }
        // 导出 Excel
        ExcelUtils.write(response, "设备责任人调整日志列表.xls", "设备责任人调整日志列表", IotDevicePersonLogRespVO.class,
                devicePersonLogs);
    }

}