/*
*  Copyright 2019-2025 Tz
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.rest;

import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.domain.BusDevice;
import me.zhengjie.modules.system.domain.BusDeviceCommand;
import me.zhengjie.modules.system.domain.dto.BusDeviceQueryCriteria;
import me.zhengjie.modules.system.domain.dto.BusTreeVo;
import me.zhengjie.modules.system.service.BusCommandService;
import me.zhengjie.modules.system.service.BusDeviceService;
import lombok.RequiredArgsConstructor;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.zhengjie.utils.PageResult;

/**
* @author tz
* @date 2025-05-20
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "系统：设备管理")
@RequestMapping("/api/busDevice")
public class BusDeviceController {

    private final BusDeviceService busDeviceService;
    private final BusCommandService busCommandService;

    @ApiOperation("根据ID返回所有子节点ID，包含自身ID")
    @GetMapping(value = "/child")
    public ResponseEntity<Object> child(@RequestParam String id) {
        Long newId = Long.parseLong(id.replace("d", "").replace("c", ""));
        Set<BusTreeVo> menuSet = new HashSet<>();
        BusTreeVo set = new BusTreeVo();
        if (id.contains("d")) {
            BusDevice entity = busDeviceService.getById(newId);
            List<BusTreeVo> list = busDeviceService.getDeviceTree(newId);
            set.setId("d" + newId);
            set.setPid("0");
            set.setName("品牌:" + entity.getBrand() +  " | " + "型号:" + entity.getModel());
            set.setRemark(entity.getLocation() + "[" + (entity.getType().equals(1) ? "3D打印机" : "摄像头") + "]");
            menuSet.add(set);
            menuSet.addAll(list);
        } else {
            BusDeviceCommand entity = busCommandService.getById(newId);
            set.setId("c" + newId);
            set.setPid("d" + entity.getDeviceId());
            set.setName(entity.getCommandName());
            set.setRemark(entity.getDescription());
            menuSet.add(set);
        }
        Set<String> ids = menuSet.stream().map(BusTreeVo::getId).collect(Collectors.toSet());
        return new ResponseEntity<>(ids,HttpStatus.OK);
    }

    @ApiOperation("查询设备指令Tree")
    @GetMapping(value = "/getDeviceTree")
    public ResponseEntity<List<BusTreeVo>> getDeviceTree(@RequestParam String pid) {
        pid = pid.replace("d", "").replace("c", "");
        return new ResponseEntity<>(busDeviceService.getDeviceTree(Long.parseLong(pid)), HttpStatus.OK);
    }

    @GetMapping("getQrCode")
    @ApiOperation("查询busDevice")
    @PreAuthorize("@el.check('busDevice:qrCode')")
    public ResponseEntity<String> getQrCode(BusDeviceQueryCriteria criteria) {
        String qrCodeUrl = busDeviceService.getQrCode(criteria.getId());
        return new ResponseEntity<>(qrCodeUrl, HttpStatus.OK);
    }

    @GetMapping
    @ApiOperation("查询busDevice")
    @PreAuthorize("@el.check('busDevice:list')")
    public ResponseEntity<PageResult<BusDevice>> queryBusDevice(BusDeviceQueryCriteria criteria){
        Page<Object> page = new Page<>(criteria.getPage(), criteria.getSize());
        return new ResponseEntity<>(busDeviceService.queryAll(criteria, page), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增busDevice")
    @ApiOperation("新增busDevice")
    @PreAuthorize("@el.check('busDevice:add')")
    public ResponseEntity<Object> createBusDevice(@Validated @RequestBody BusDevice resources){
        busDeviceService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改busDevice")
    @ApiOperation("修改busDevice")
    @PreAuthorize("@el.check('busDevice:edit')")
    public ResponseEntity<Object> updateBusDevice(@Validated @RequestBody BusDevice resources){
        busDeviceService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除busDevice")
    @ApiOperation("删除busDevice")
    @PreAuthorize("@el.check('busDevice:del')")
    public ResponseEntity<Object> deleteBusDevice(@ApiParam(value = "传ID数组[]") @RequestBody List<Long> ids) {
        busDeviceService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}