package com.tashow.cloud.system.controller.admin.logger;

import com.tashow.cloud.common.pojo.CommonResult;
import com.tashow.cloud.common.pojo.PageParam;
import com.tashow.cloud.common.pojo.PageResult;
import com.tashow.cloud.common.util.object.BeanUtils;
import com.tashow.cloud.excel.excel.core.util.ExcelUtils;
import com.tashow.cloud.mybatis.translate.core.TranslateUtils;
import com.tashow.cloud.system.controller.admin.logger.vo.operatelog.OperateLogPageReqVO;
import com.tashow.cloud.system.controller.admin.logger.vo.operatelog.OperateLogRespVO;
import com.tashow.cloud.system.dal.dataobject.logger.OperateLogDO;
import com.tashow.cloud.system.service.logger.OperateLogService;
import com.tashow.cloud.web.apilog.core.annotation.ApiAccessLog;
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.RestController;

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

import static com.tashow.cloud.common.pojo.CommonResult.success;
import static com.tashow.cloud.web.apilog.core.enums.OperateTypeEnum.EXPORT;

/**
 * 管理后台 - 操作日志
 */
@RestController
@RequestMapping("/system/operate-log")
@Validated
public class OperateLogController {

    @Resource
    private OperateLogService operateLogService;

    /**
     * 查看操作日志分页列表
     */
    @GetMapping("/page")
    @PreAuthorize("@ss.hasPermission('system:operate-log:query')")
    public CommonResult<PageResult<OperateLogRespVO>> pageOperateLog(
            @Valid OperateLogPageReqVO pageReqVO) {
        PageResult<OperateLogDO> pageResult = operateLogService.getOperateLogPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, OperateLogRespVO.class));
    }

    /**
     * 导出操作日志
     */
    @GetMapping("/export")
    @PreAuthorize("@ss.hasPermission('system:operate-log:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportOperateLog(HttpServletResponse response, @Valid OperateLogPageReqVO exportReqVO)
            throws IOException {
        exportReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<OperateLogDO> list = operateLogService.getOperateLogPage(exportReqVO).getList();
        ExcelUtils.write(
                response,
                "操作日志.xls",
                "数据列表",
                OperateLogRespVO.class,
                TranslateUtils.translate(BeanUtils.toBean(list, OperateLogRespVO.class)));
    }
}
