package tech.easyflow.admin.controller.dashboard;

import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.easyflow.admin.model.dashboard.DashboardOverviewQuery;
import tech.easyflow.admin.model.dashboard.DashboardOverviewVo;
import tech.easyflow.admin.model.dashboard.DashboardUserRankItemVo;
import tech.easyflow.admin.model.dashboard.DashboardUserRankQuery;
import tech.easyflow.admin.service.dashboard.DashboardService;
import tech.easyflow.common.domain.Result;
import tech.easyflow.common.satoken.util.SaTokenUtil;

import jakarta.servlet.http.HttpServletResponse;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 管理端工作台统计接口。
 */
@RestController
@RequestMapping("/api/v1/dashboard")
public class DashboardController {

    private final DashboardService dashboardService;

    public DashboardController(DashboardService dashboardService) {
        this.dashboardService = dashboardService;
    }

    @GetMapping("/overview")
    @SaCheckPermission("/api/v1/dashboard/query")
    public Result<DashboardOverviewVo> overview(DashboardOverviewQuery query) {
        return Result.ok(dashboardService.getOverview(SaTokenUtil.getLoginAccount(), query));
    }

    @GetMapping("/user-ranks")
    @SaCheckPermission("/api/v1/dashboard/query")
    public Result<List<DashboardUserRankItemVo>> userRanks(DashboardUserRankQuery query) {
        return Result.ok(dashboardService.getUserRanks(SaTokenUtil.getLoginAccount(), query));
    }

    @GetMapping(value = "/user-ranks/export", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    @SaCheckPermission("/api/v1/dashboard/query")
    public void exportUserRanks(DashboardUserRankQuery query, HttpServletResponse response) throws Exception {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String fileName = URLEncoder.encode("dashboard_user_ranks_" + timestamp, "UTF-8")
                .replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        dashboardService.exportUserRanks(
                SaTokenUtil.getLoginAccount(),
                query,
                response.getOutputStream()
        );
    }
}
