package com.gxwebsoft.oa.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.utils.BtUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.oa.entity.AppUser;
import com.gxwebsoft.oa.entity.Assets;
import com.gxwebsoft.oa.entity.AssetsUser;
import com.gxwebsoft.oa.param.AssetsParam;
import com.gxwebsoft.oa.service.AssetsService;
import com.gxwebsoft.oa.service.AssetsUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 服务器资产记录表控制器
 *
 * @author WebSoft
 * @since 2022-11-16 11:13:16
 */
@Api(tags = "服务器资产记录表管理")
@RestController
@RequestMapping("/api/oa/assets")
public class AssetsController extends BaseController {
    @Resource
    private AssetsService assetsService;
    @Resource
    private AssetsUserService assetsUserService;
    @Resource
    private BtUtil btUtil;

    @PreAuthorize("hasAuthority('oa:assets:list')")
    @OperationLog
    @ApiOperation("分页查询服务器资产记录表")
    @GetMapping("/page")
    public ApiResult<PageResult<Assets>> page(AssetsParam param) {
        final User loginUser = getLoginUser();
        final Integer userId = loginUser.getUserId();
        loginUser.getRoles().forEach(d -> {
          if(!StrUtil.equals(d.getRoleCode(),"superAdmin") && !StrUtil.equals(d.getRoleCode(),"admin")){
            // 非管理员按项目成员权限显示
            param.setSceneType("NotAdministrator");
            final List<AssetsUser> list = assetsUserService.list(new LambdaQueryWrapper<AssetsUser>().eq(AssetsUser::getUserId, userId));
            final Set<Integer> collect = list.stream().map(AssetsUser::getAssetsId).collect(Collectors.toSet());
            if(!CollectionUtils.isEmpty(collect)){
              param.setAssetsIds(collect);
            }
          }
        });
        // 非管理员并且无分配资源
        if(param.getSceneType() != null && param.getSceneType().equals("NotAdministrator") && CollectionUtils.isEmpty(param.getAssetsIds())){
          final PageResult<Assets> result = new PageResult<>();
          result.setList(new ArrayList<>());
          result.setCount(0L);
          return success(result);
        }
        // 返回查询结果
        return success(assetsService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('oa:assets:list')")
    @OperationLog
    @ApiOperation("查询全部服务器资产记录表")
    @GetMapping()
    public ApiResult<List<Assets>> list(AssetsParam param) {
        // 使用关联查询
        return success(assetsService.listRel(param));
    }

    @PreAuthorize("hasAuthority('oa:assets:list')")
    @OperationLog
    @ApiOperation("根据id查询服务器资产记录表")
    @GetMapping("/{id}")
    public ApiResult<Assets> get(@PathVariable("id") Integer id) {
        final Assets assets = assetsService.getByIdRel(id);
        final BtUtil client = btUtil.client(id);
        final String systemTotal = client.getSystemTotal();
        final String diskInfo = client.getDiskInfo();
        assets.setSystemTotal(systemTotal);
        assets.setDiskInfo(diskInfo);
        // 使用关联查询
        return success(assets);
    }

    @PreAuthorize("hasAuthority('oa:assets:save')")
    @OperationLog
    @ApiOperation("添加服务器资产记录表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody Assets assets) {
        // 记录当前登录用户id、租户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
          assets.setUserId(loginUser.getUserId());
        }
        if (assetsService.count(new LambdaQueryWrapper<Assets>().eq(Assets::getCode,assets.getCode())) > 0) {
          return fail("该IP地址已存在");
        }
        if (assetsService.save(assets)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('oa:assets:update')")
    @OperationLog
    @ApiOperation("修改服务器资产记录表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Assets assets) {
        if (assetsService.updateById(assets)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('oa:assets:remove')")
    @OperationLog
    @ApiOperation("删除服务器资产记录表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (assetsService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('oa:assets:save')")
    @OperationLog
    @ApiOperation("批量添加服务器资产记录表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<Assets> list) {
        if (assetsService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('oa:assets:update')")
    @OperationLog
    @ApiOperation("批量修改服务器资产记录表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<Assets> batchParam) {
        if (batchParam.update(assetsService, "assets_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('oa:assets:remove')")
    @OperationLog
    @ApiOperation("批量删除服务器资产记录表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (assetsService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }
}
