package com.czg.controller.admin;

import com.czg.excel.ExcelExportUtil;
import com.czg.order.entity.ShopProdStatistic;
import com.czg.order.param.SaleSummaryCountParam;
import com.czg.order.service.ShopProdStatisticService;
import com.czg.order.vo.SaleSummaryCountVo;
import com.czg.resp.CzgResult;
import com.czg.sa.StpKit;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

/**
 * 销量统计
 *
 * @author tankaikai
 * @since 2025-03-07 15:25
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/admin/sale/summary")
public class SaleSummaryController {
    @Resource
    private ShopProdStatisticService prodStatisticService;

    /**
     * 统计
     */
    @GetMapping("count")
    //@SaAdminCheckPermission("saleSummary:count")
    public CzgResult<SaleSummaryCountVo> summaryCount(SaleSummaryCountParam param) {
        if (param.getShopId() == null) {
            param.setShopId(StpKit.USER.getShopId());
        }
        SaleSummaryCountVo data = prodStatisticService.summaryCount(param);
        return CzgResult.success(data);
    }

    /**
     * 分页
     */
    @GetMapping("page")
    //@SaAdminCheckPermission("saleSummary:page")
    public CzgResult<List<ShopProdStatistic>> summaryPage(SaleSummaryCountParam param) {
        if (param.getShopId() == null) {
            param.setShopId(StpKit.USER.getShopId());
        }
        List<ShopProdStatistic> list = prodStatisticService.getArchiveTradeData(param);
        return CzgResult.success(list);
    }

    /**
     * 商品报表导出
     */
    @GetMapping("/export")
    public void summaryExport(SaleSummaryCountParam param, HttpServletResponse response) {
        if (param.getShopId() == null) {
            param.setShopId(StpKit.USER.getShopId());
        }
        ExcelExportUtil.exportToResponse(prodStatisticService.getArchiveTradeData(param), ShopProdStatistic.class, "销售统计明细", response);
    }


    /**
     * 商品报表打印
     */
    @GetMapping("/print")
    public CzgResult<Void> summaryPrint(SaleSummaryCountParam param) {
        LocalDateTime now = LocalDateTime.now();
        LocalTime nowTime = now.toLocalTime();
        // 起始 00:00，结束 05:20
        LocalTime start = LocalTime.of(0, 0);
        LocalTime end = LocalTime.of(5, 20);

        if (nowTime.isAfter(start) && nowTime.isBefore(end)) {
            // 在 00:00 ~ 05:20 区间内
            return CzgResult.failure("当前时间不支持打印，打印时间：5点20至24点");
        }
        if (param.getShopId() == null) {
            param.setShopId(StpKit.USER.getShopId());
        }
        prodStatisticService.summaryPrint(param);
        return CzgResult.success();
    }
}
