package cd.casic.module.machine.controller;

import cd.casic.framework.commons.pojo.CommonResult;
import cd.casic.framework.commons.pojo.PageResult;
import cd.casic.framework.commons.util.object.BeanUtils;
import cd.casic.module.machine.controller.vo.MachineProxyVO;
import cd.casic.module.machine.dal.dataobject.MachineProxyDO;
import cd.casic.module.machine.service.MachineProxyService;
import cn.hutool.core.collection.CollUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

import static cd.casic.framework.commons.pojo.CommonResult.success;

/**
 * 机器代理控制器
 */
@RestController
@RequestMapping("/ci/machineProxy")
@Tag(name = "机器代理管理")
@Validated
public class MachineProxyController {

    @Resource
    private MachineProxyService machineProxyService;

    @PostMapping("/create")
    @Operation(summary = "注册新的机器代理")
//    @PreAuthorize("@ss.hasPermission('ci:machineProxy:create')")
    public CommonResult<Long> createProxy(@Valid @RequestBody MachineProxyVO machineProxyVO) {
        Long id = machineProxyService.createProxy(machineProxyVO);
        return success(id);
    }

    @PutMapping("/update")
    @Operation(summary = "修改代理")
//    @PreAuthorize("@ss.hasPermission('ci:machineProxy:update')")
    public CommonResult<Boolean> updateProxy(@Valid @RequestBody MachineProxyVO machineProxyVO) {
        machineProxyService.updateProxy(machineProxyVO);
        return success(true);
    }

    @PostMapping("/list")
    @Operation(summary = "获取代理列表")
    public CommonResult<PageResult<MachineProxyVO>> getProxyPage(@Valid @RequestBody MachineProxyVO machineProxyVO) {
        PageResult<MachineProxyDO> pageResult = machineProxyService.getProxyPage(machineProxyVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(new PageResult<>(pageResult.getTotal()));
        }
        return success(BeanUtils.toBean(pageResult, MachineProxyVO.class));
    }

    @GetMapping("/allStatus")
    @Operation(summary = "获取所有代理的状态统计")
    public CommonResult<Map<Integer, Long>> getStatusStatistics() {
        return success(machineProxyService.getAllProxyStatus());
    }

    @DeleteMapping("delete")
    @Operation(summary = "删除代理")
    public CommonResult<Boolean> delete(@RequestParam("id") Long id) {
        machineProxyService.delete(id);
        return success(true);
    }

    @DeleteMapping("/deleteList")
    @Operation(summary = "批量删除代理")
//    @PreAuthorize("@ss.hasPermission('ci:machineProxy:delete')")
    public CommonResult<Boolean> deleteProxyList(@RequestParam String ids) {
        machineProxyService.deleteProxyList(ids);
        return success(true);
    }

}
