package cn.iocoder.yudao.module.smartfactory.controller.admin.device.cameradevice;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.smartfactory.controller.admin.device.cameradevice.vo.CameraDevicePageReqVO;
import cn.iocoder.yudao.module.smartfactory.controller.admin.device.cameradevice.vo.CameraDeviceRespVO;
import cn.iocoder.yudao.module.smartfactory.controller.admin.device.cameradevice.vo.CameraDeviceSaveReqVO;
import cn.iocoder.yudao.module.smartfactory.controller.admin.device.cameradevice.vo.CameraUpdateStatusReqVO;
import cn.iocoder.yudao.module.smartfactory.controller.admin.factoryinfo.vo.FactorySimpleRespVO;
import cn.iocoder.yudao.module.smartfactory.controller.admin.factoryinfo.vo.FactoryTreeRespVO;
import cn.iocoder.yudao.module.smartfactory.convert.cameradevice.CameraDeviceConvert;
import cn.iocoder.yudao.module.smartfactory.dal.dataobject.device.cameradevice.CameraDeviceDO;
import cn.iocoder.yudao.module.smartfactory.dal.dataobject.factoryinfo.FactoryInfoDO;
import cn.iocoder.yudao.module.smartfactory.service.device.cameradevice.CameraDeviceService;
import cn.iocoder.yudao.module.smartfactory.service.factoryinfo.FactoryInfoService;
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.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;

@Tag(name = "管理后台 - 设备-监控摄像头")
@RestController
@RequestMapping("/smartfactory/camera-device")
@Validated
public class CameraDeviceController {

    @Resource
    private CameraDeviceService cameraDeviceService;

    @Resource
    private FactoryInfoService factoryInfoService;

    @PostMapping("/create")
    @Operation(summary = "创建设备-监控摄像头")
    @PreAuthorize("@ss.hasPermission('smartfactory:camera-device:create')")
    public CommonResult<Long> createCameraDevice(@Valid @RequestBody CameraDeviceSaveReqVO createReqVO) {
        return success(cameraDeviceService.createCameraDevice(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新设备-监控摄像头")
    @PreAuthorize("@ss.hasPermission('smartfactory:camera-device:update')")
    public CommonResult<Boolean> updateCameraDevice(@Valid @RequestBody CameraDeviceSaveReqVO updateReqVO) {
        cameraDeviceService.updateCameraDevice(updateReqVO);
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(summary = "更新设备-监控摄像头状态")
    @PreAuthorize("@ss.hasPermission('smartfactory:camera-device:update')")
    public CommonResult<Boolean> updateCameraDevice(@Valid @RequestBody CameraUpdateStatusReqVO updateReqVO) {

        cameraDeviceService.updateCameraDeviceStatus(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除设备-监控摄像头")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('smartfactory:camera-device:delete')")
    public CommonResult<Boolean> deleteCameraDevice(@RequestParam("id") Long id) {
        cameraDeviceService.deleteCameraDevice(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得设备-监控摄像头")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('smartfactory:camera-device:query')")
    public CommonResult<CameraDeviceRespVO> getCameraDevice(@RequestParam("id") Long id) {
        CameraDeviceDO cameraDevice = cameraDeviceService.getCameraDevice(id);
        return success(BeanUtils.toBean(cameraDevice, CameraDeviceRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得设备-监控摄像头分页")
    @PreAuthorize("@ss.hasPermission('smartfactory:camera-device:query')")
    public CommonResult<PageResult<CameraDeviceRespVO>> getCameraDevicePage(@Valid CameraDevicePageReqVO pageReqVO) {

        PageResult<CameraDeviceDO> pageResult = cameraDeviceService.getCameraDevicePage(pageReqVO);
        PageResult<CameraDeviceRespVO> pageData = BeanUtils.toBean(pageResult, CameraDeviceRespVO.class);

        List<CameraDeviceRespVO> pageList = pageData.getList();

        // 获得工厂信息
        List<FactoryInfoDO> factoryInfoDOS = factoryInfoService.getFactoryList(convertList(pageList, CameraDeviceRespVO::getFactoryId));
        Map<Long, FactoryInfoDO> factoryMap = convertMap(factoryInfoDOS, FactoryInfoDO::getId);
        pageList.forEach(data -> {

            data.setFactoryName(factoryMap.get(data.getFactoryId()).getName());
        });
        return success(pageData);
    }

    @GetMapping("/camera-tree")
    @Operation(summary = "获得设备-监控摄像头Tree")
    @PreAuthorize("@ss.hasPermission('smartfactory:camera-device:query')")
    public CommonResult<FactoryTreeRespVO> getCameraDeviceTree(@RequestParam(value = "factoryId", required = false) Long factoryId,
                                                               @RequestParam(value = "name", required = false) String name) {

        FactoryTreeRespVO data = new FactoryTreeRespVO();
        List<FactorySimpleRespVO> info = new ArrayList<>();

        // 获取工厂信息
        List<FactoryInfoDO> factoryInfo = factoryInfoService.getFactoryList(factoryId, name);
        List<Long> factoryIds = convertList(factoryInfo, FactoryInfoDO::getId);
        // 获取监控设备信息
        List<CameraDeviceDO> cameraDeviceDOS = cameraDeviceService.getListCameraByStatus(factoryIds);
        Map<Long, List<CameraDeviceDO>> cameraMap = cameraDeviceDOS.stream().collect(Collectors.groupingBy(CameraDeviceDO::getFactoryId));

        if (!CollUtil.isEmpty(factoryInfo)) {

            Map<String, List<FactoryInfoDO>> infoDOMap = factoryInfo.stream().collect(Collectors.groupingBy(FactoryInfoDO::getType));
            for (String key : infoDOMap.keySet()) {

                switch (key) {
                    case "1":
                        data = BeanUtils.toBean(infoDOMap.get(key).get(0), FactoryTreeRespVO.class);
                        break;
                    case "2":
                        info.addAll(0, CameraDeviceConvert.INSTANCE.convertList(infoDOMap.get(key), cameraMap));
                        break;
                    case "3":
                        info.addAll(CameraDeviceConvert.INSTANCE.convertList(infoDOMap.get(key), cameraMap));
                        break;
                }
            }
            data.setSubsidiary(info);
        }

        return success(data);
    }
}