package com.gxwebsoft.oa.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.utils.BtUtil;
import com.gxwebsoft.common.core.utils.RedisUtil;
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.Role;
import com.gxwebsoft.common.system.entity.User;
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 com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.entity.OrderInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.gxwebsoft.common.core.constants.AppUserConstants.ADMINISTRATOR;

/**
 * 服务器资产记录表控制器
 *
 * @author 科技小王子
 * @since 2023-10-26 21:08:27
 */
@Api(tags = "服务器资产记录表管理")
@RestController
@RequestMapping("/api/oa/assets")
public class AssetsController extends BaseController {
    @Resource
    private AssetsService assetsService;
    @Resource
    private AssetsUserService assetsUserService;
    @Resource
    private BtUtil btUtil;
    @Resource
    private RedisUtil redisUtil;

    @ApiOperation("统计信息")
    @GetMapping("/data")
    public ApiResult<Map<String, Integer>> data() {
      final User loginUser = getLoginUser();
      final Integer userId = loginUser.getUserId();
      final List<String> collect1 = loginUser.getRoles().stream().map(Role::getRoleCode).collect(Collectors.toList());
      Map<String, Integer> data = new HashMap<>();
      if (collect1.contains("superAdmin") || collect1.contains("admin")) {
        Integer totalNum = assetsService.count(
          new LambdaQueryWrapper<Assets>()
        );
        Integer totalNum1 = assetsService.count(
          new LambdaQueryWrapper<Assets>()
            .gt(Assets::getEndTime, LocalDateTime.now())
//            .eq(Assets::getStatus, "运行中")
        );
        Integer totalNum2 = assetsService.count(
          new LambdaQueryWrapper<Assets>()
            .lt(Assets::getEndTime, LocalDateTime.now())
        );
        Integer totalNum3 = assetsService.count(
          new LambdaQueryWrapper<Assets>()
            .eq(Assets::getStatus, "已销毁")
        );
        data.put("totalNum", totalNum);
        data.put("totalNum1", totalNum1);
        data.put("totalNum2", totalNum2);
        data.put("totalNum3", totalNum3);

        // 处理已过期主机
        String key = "Assets:update:".concat(loginUser.getTenantId().toString());
        if(redisUtil.get(key) == null){
          final List<Assets> list = assetsService.list(new LambdaQueryWrapper<Assets>().lt(Assets::getEndTime, LocalDateTime.now()));
          list.forEach(d -> {
            d.setStatus("已到期");
          });
          if (assetsService.updateBatchById(list)) {
            redisUtil.set(key,1,1L, TimeUnit.DAYS);
          }
        }
        return success(data);
      }
      // 非管理员
      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());
      Integer totalNum = assetsService.count(
        new LambdaQueryWrapper<Assets>().in(Assets::getAssetsId,collect)
      );
      Integer totalNum1 = assetsService.count(
        new LambdaQueryWrapper<Assets>()
          .gt(Assets::getEndTime, LocalDateTime.now())
          .in(Assets::getAssetsId,collect)
      );
      Integer totalNum2 = assetsService.count(
        new LambdaQueryWrapper<Assets>()
          .lt(Assets::getEndTime, LocalDateTime.now())
          .in(Assets::getAssetsId,collect)
      );
      Integer totalNum3 = assetsService.count(
        new LambdaQueryWrapper<Assets>()
          .eq(Assets::getStatus, "已销毁")
          .in(Assets::getAssetsId,collect)
      );

      data.put("totalNum", totalNum);
      data.put("totalNum1", totalNum1);
      data.put("totalNum2", totalNum2);
      data.put("totalNum3", totalNum3);
      return success(data);
    }

    @ApiOperation("分页查询服务器资产记录表")
    @GetMapping("/page")
    public ApiResult<PageResult<Assets>> page(AssetsParam param) {
        final User loginUser = getLoginUser();
        final Integer userId = loginUser.getUserId();
        final List<String> collect1 = loginUser.getRoles().stream().map(Role::getRoleCode).collect(Collectors.toList());
        if (collect1.contains("superAdmin") || collect1.contains("admin")) {
          // 返回查询结果
          return success(assetsService.pageRel(param));
        }

        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);
        }
        return success(assetsService.pageRel(param));
    }

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

    @ApiOperation("根据id查询服务器资产记录表")
    @GetMapping("/{id}")
    public ApiResult<Assets> get(@PathVariable("id") Integer id) {
        final Assets assets = assetsService.getByIdRel(id);
        // 查询宝塔接口
        if(StrUtil.isNotBlank(assets.getBtSign())){
          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);
    }

    @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)) {
            // 添加应用管理员
            if (loginUser != null) {
              final AssetsUser assetsUser = new AssetsUser();
              assetsUser.setUserId(loginUser.getUserId());
              assetsUser.setNickname(loginUser.getNickname());
              assetsUser.setAssetsId(assets.getAssetsId());
              assetsUser.setRole(ADMINISTRATOR);
              assetsUserService.save(assetsUser);
            }
            return success("添加成功");
        }
        return fail("添加失败");
    }

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

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

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

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

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