package com.cf.imes.module.system.controller.admin.machine;

import com.cf.imes.framework.common.pojo.CommonResult;
import com.cf.imes.framework.common.pojo.PageResult;
import com.cf.imes.module.system.controller.admin.machine.vo.*;
import com.cf.imes.module.system.dal.dataobject.machine.MachineDO;
import com.cf.imes.module.system.dal.dataobject.machinetemplate.MachineTemplateDO;
import com.cf.imes.module.system.service.machine.MachineService;
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.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

import static com.cf.imes.framework.common.pojo.CommonResult.success;

/**
 * @author Beal
 */
@RestController
@Tag(name = "机台授权")
@RequestMapping("/system/machine-auth")
public class MachineAuthController {
    
    @Resource
    private MachineService machineService;

    @PostMapping("organ-auth")
    @Operation(summary = "组织机台授权")
    @PreAuthorize("@ss.hasPermission('machine-template::query')")
    public CommonResult<Boolean> auth(@RequestBody MachineOrgAuthReq vo) {
        return success(machineService.auth(vo));
    }

    @GetMapping("organ-page")
    @Operation(summary = "组织机台授权分页列表")
    @PreAuthorize("@ss.hasPermission('machine-template::query')")
    public CommonResult<PageResult<OrganMachineResp>> organTemplatePage(OrganMachinePage page) {
        return success(machineService.organMachinePage(page));
    }

    @GetMapping("organ-by-organId")
    @Operation(summary = "根据组织id查询组织机台授权")
    @PreAuthorize("@ss.hasPermission('machine-template::query')")
    @Parameter(name = "organId", description = "组织id", required = true, example = "1")
    public CommonResult<OrganMachineResp> organTemplateByOrganId(@RequestParam Long organId ) {
        return success(machineService.organMachineByOrganId(organId));
    }

    @GetMapping("page-machine-auth")
    @Operation(summary = "授权机台分页")
    @PreAuthorize("@ss.hasPermission('machine-template::query')")
    public CommonResult<PageResult<MachineAuthResp>> pageTemplateAuth(MachinePageReqVO pageParam) {
        PageResult<MachineDO> page = machineService.page(pageParam);
        List<MachineAuthResp> list = page.getList().stream().map(e->MachineAuthResp.builder()
                .id(e.getId())
                .machineType(e.getMachineType())
                .machineName(e.getName())
                .organId(e.getOrganId())
                .build()
        ).collect(Collectors.toList());

        return success(new PageResult<MachineAuthResp>(list, page.getTotal()));
    }
    
}
