package com.njcn.rdms.module.system.controller.admin.logger;

import com.njcn.rdms.framework.apilog.core.annotation.ApiAccessLog;
import com.njcn.rdms.framework.common.pojo.CommonResult;
import com.njcn.rdms.framework.common.pojo.PageParam;
import com.njcn.rdms.framework.common.pojo.PageResult;
import com.njcn.rdms.framework.common.util.collection.CollectionUtils;
import com.njcn.rdms.framework.common.util.object.BeanUtils;
import com.njcn.rdms.framework.excel.core.util.ExcelUtils;
import com.njcn.rdms.module.system.controller.admin.logger.vo.apiaccesslog.ApiAccessLogPageReqVO;
import com.njcn.rdms.module.system.controller.admin.logger.vo.apiaccesslog.ApiAccessLogRespVO;
import com.njcn.rdms.module.system.dal.dataobject.logger.ApiAccessLogDO;
import com.njcn.rdms.module.system.dal.dataobject.user.AdminUserDO;
import com.njcn.rdms.module.system.service.logger.ApiAccessLogService;
import com.njcn.rdms.module.system.service.user.AdminUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static com.njcn.rdms.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static com.njcn.rdms.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - API 访问日志")
@RestController
@RequestMapping("/system/api-access-log")
@Validated
public class ApiAccessLogController {

    @Resource
    private ApiAccessLogService apiAccessLogService;
    @Resource
    private AdminUserService adminUserService;

    @GetMapping("/get")
    @Operation(summary = "获得 API 访问日志")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:api-access-log:query')")
    public CommonResult<ApiAccessLogRespVO> getApiAccessLog(@RequestParam("id") Long id) {
        ApiAccessLogRespVO respVO = BeanUtils.toBean(apiAccessLogService.getApiAccessLog(id), ApiAccessLogRespVO.class);
        fillUserNicknames(Collections.singletonList(respVO));
        return success(respVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得API 访问日志分页")
    @PreAuthorize("@ss.hasPermission('system:api-access-log:query')")
    public CommonResult<PageResult<ApiAccessLogRespVO>> getApiAccessLogPage(@Valid ApiAccessLogPageReqVO pageReqVO) {
        PageResult<ApiAccessLogDO> pageResult = apiAccessLogService.getApiAccessLogPage(pageReqVO);
        PageResult<ApiAccessLogRespVO> respPageResult = BeanUtils.toBean(pageResult, ApiAccessLogRespVO.class);
        fillUserNicknames(respPageResult.getList());
        return success(respPageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出API 访问日志 Excel")
    @PreAuthorize("@ss.hasPermission('system:api-access-log:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportApiAccessLogExcel(@Valid ApiAccessLogPageReqVO exportReqVO,
                                        HttpServletResponse response) throws IOException {
        exportReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ApiAccessLogRespVO> respVOList = BeanUtils.toBean(
                apiAccessLogService.getApiAccessLogPage(exportReqVO).getList(), ApiAccessLogRespVO.class);
        fillUserNicknames(respVOList);
        // 导出 Excel
        ExcelUtils.write(response, "API 访问日志.xls", "数据", ApiAccessLogRespVO.class,
                respVOList);
    }

    private void fillUserNicknames(List<ApiAccessLogRespVO> respVOList) {
        if (respVOList == null || respVOList.isEmpty()) {
            return;
        }
        Map<Long, AdminUserDO> userMap = adminUserService.getUserMap(
                CollectionUtils.convertSet(respVOList, ApiAccessLogRespVO::getUserId));
        respVOList.forEach(respVO -> {
            AdminUserDO user = userMap.get(respVO.getUserId());
            if (user != null) {
                respVO.setUserNickname(user.getNickname());
            }
        });
    }

}

