package com.yiqi.admin.controller.settlement;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yiqi.common.constant.UrlConstants;
import com.yiqi.common.core.controller.BaseController;
import com.yiqi.common.core.domain.AjaxResult;
import com.yiqi.common.core.page.TableDataInfo;
import com.yiqi.common.utils.DateUtils;
import com.yiqi.common.utils.poi.ExcelUtil;
import com.yiqi.core.domain.SettlementStoreStatistics;
import com.yiqi.core.service.ISettlementStoreStatisticsService;
import com.yiqi.settlement.domain.dto.StoreChargeStatistics;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController
@RequestMapping(UrlConstants.managerApi + "/settlement/store/statistics")
public class SettlementStoreStatisticsController extends BaseController {

    @Autowired
    private ISettlementStoreStatisticsService settlementStoreStatisticsService;

    /**
     * 获取门店经营日报数据
     */
    @GetMapping("/dashboard")
    public AjaxResult dashboard() {
        // 获取订单统计数据
        SettlementStoreStatistics orderStats = settlementStoreStatisticsService.orderStatistics(getStoreId(), null, null);

        // 获取充值统计数据
        StoreChargeStatistics chargeStats = settlementStoreStatisticsService.chargeTotal(getStoreId());

        Map<String, Object> result = new HashMap<>();
        result.put("orderStats", orderStats);
        result.put("chargeStats", chargeStats);

        return AjaxResult.success(result);
    }

    /**
     * 获取门店经营日报数据
     */
    @GetMapping("/daily")
    public AjaxResult getDailyStatistics(@RequestParam("date") String date) {
        Date queryDate = DateUtils.parseDate(date);
        Long storeId = getStoreId();

        // 获取订单统计数据
        SettlementStoreStatistics orderStats = settlementStoreStatisticsService.generateStoreStatistics(queryDate, storeId);

        // 获取充值统计数据
        StoreChargeStatistics chargeStats = settlementStoreStatisticsService.generateChargeStatistics(queryDate, storeId);

        Map<String, Object> result = new HashMap<>();
        result.put("orderStats", orderStats);
        result.put("chargeStats", chargeStats);

        return AjaxResult.success(result);
    }

    /**
     * 同步每日数据
     */
    @GetMapping("/sync")
    public AjaxResult orderSync() {
        Date queryDate = DateUtils.getNowDate();
        Long storeId = getStoreId();
        if (storeId != null) {
        } else {
            settlementStoreStatisticsService.generateDayStatistics(queryDate);
        }
        return AjaxResult.success();
    }

    /**
     * 获取门店经营日报趋势数据
     */
    @GetMapping("/trend")
    public AjaxResult getDailyTrend(@RequestParam("startDate") String startDate,
                                    @RequestParam("endDate") String endDate) {
        Date start = DateUtils.parseDate(startDate);
        Date end = DateUtils.parseDate(endDate);
        Long storeId = getLoginUser().getStoreId();

        // 获取订单统计趋势
        List<SettlementStoreStatistics> orderTrend = settlementStoreStatisticsService.queryStoreStatisticsByDate(storeId, start, end);

        // 获取充值统计趋势
        List<StoreChargeStatistics> chargeTrend = settlementStoreStatisticsService.generateChargeStatisticsByDate(storeId, start, end);

        Map<String, Object> result = new HashMap<>();
        result.put("orderTrend", orderTrend);
        result.put("chargeTrend", chargeTrend);

        return AjaxResult.success(result);
    }

    /**
     * 获取门店每日交易统计列表
     */
    @GetMapping("/list")
    public TableDataInfo list(@RequestParam(required = false) String startDate,
                              @RequestParam(required = false) String endDate,
                              @RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "15") Integer pageSize) {

        startPage();
        Date start = startDate != null ? DateUtils.parseDate(startDate) : DateUtils.addDays(new Date(), -14);
        Date end = endDate != null ? DateUtils.parseDate(endDate) : new Date();
        Long storeId = getLoginUser().getStoreId();

        List<SettlementStoreStatistics> list = settlementStoreStatisticsService
                .queryStoreStatisticsByDate(storeId, start, end);
        return getDataTable(list);
    }

    /**
     * 获取门店每日充值统计列表
     */
    @GetMapping("/charge/list")
    public TableDataInfo chargeList(@RequestParam(required = false) String startDate,
                                    @RequestParam(required = false) String endDate,
                                    @RequestParam(required = false) Integer sort,
                                    @RequestParam(defaultValue = "1") Integer pageNum,
                                    @RequestParam(defaultValue = "15") Integer pageSize) {
        Date start = startDate != null ? DateUtils.parseDate(startDate) : DateUtils.addDays(new Date(), -14);
        Date end = endDate != null ? DateUtils.parseDate(endDate) : new Date();
        Long storeId = getLoginUser().getStoreId();
        List<StoreChargeStatistics> statisticsList = settlementStoreStatisticsService.generateChargeStatisticsByDate(storeId, start, end);
        if (sort != null && sort == 1) {
            statisticsList.sort(Comparator.comparing(StoreChargeStatistics::getDay, Comparator.reverseOrder()));
        }
        Long totalCount = (long) statisticsList.size();
        // 4. 处理分页
        if (pageNum != null && pageSize != null && pageNum > 0 && pageSize > 0) {
            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, statisticsList.size());
            if (startIndex >= statisticsList.size()) {
                statisticsList = Collections.emptyList();
            }
            statisticsList = statisticsList.subList(startIndex, endIndex);
        }
        return getDataTable(statisticsList, totalCount);
    }

    /**
     * 获取门店每日充值统计列表
     */
    @GetMapping("/charge/bystore")
    public TableDataInfo chargeByStore(@RequestParam(required = false) String startDate,
                                       @RequestParam(required = false) Integer storeType,
                                       @RequestParam(required = false) Long storeId,
                                       @RequestParam(defaultValue = "1") Integer pageNum,
                                       @RequestParam(defaultValue = "10") Integer pageSize) {
        Date start = startDate != null ? DateUtils.parseDate(startDate) : DateUtils.addDays(new Date(), -1);
        Page<StoreChargeStatistics> chargeTrend = settlementStoreStatisticsService.generateChargeStatisticsByStore(storeId, storeType, start, pageSize, pageNum);
        return getDataTable(chargeTrend.getRecords(), chargeTrend.getTotal());
    }

    /**
     * 获取门店每日充值统计列表
     */
    @PostMapping("/charge/export/bystore")
    public void chargeExport(HttpServletResponse response, @RequestParam(required = false) String startDate,
                             @RequestParam(required = false) Integer storeType,
                             @RequestParam(required = false) Long storeId) {
        Date start = startDate != null ? DateUtils.parseDate(startDate) : DateUtils.addDays(new Date(), -1);
        Page<StoreChargeStatistics> chargeTrend = settlementStoreStatisticsService.generateChargeStatisticsByStore(storeId, storeType, start, 500, 1);
        ExcelUtil<StoreChargeStatistics> util = new ExcelUtil<>(StoreChargeStatistics.class);
        util.exportExcel(response, chargeTrend.getRecords(), "门店每日充值统计");
    }

    /**
     * 获取门店每日充值统计列表
     */
    @PostMapping("/charge/export")
    public void chargeExport(HttpServletResponse response, @RequestParam(required = false) String startDate,
                             @RequestParam(required = false) String endDate) {

        Date start = startDate != null ? DateUtils.parseDate(startDate) : DateUtils.addDays(new Date(), -14);
        Date end = endDate != null ? DateUtils.parseDate(endDate) : new Date();
        Long storeId = getLoginUser().getStoreId();
        List<StoreChargeStatistics> chargeTrend = settlementStoreStatisticsService.generateChargeStatisticsByDate(storeId, start, end);
        ExcelUtil<StoreChargeStatistics> util = new ExcelUtil<>(StoreChargeStatistics.class);
        util.exportExcel(response, chargeTrend, "门店每日充值统计");
    }

    /**
     * 获取门店每日交易统计列表
     */
    @GetMapping("/list/bystore")
    public TableDataInfo listByStore(@RequestParam(required = false) String startDate,
                                     @RequestParam(required = false) String endDate,
                                     @RequestParam(required = false) Long storeId,
                                     @RequestParam(defaultValue = "1") Integer pageNum,
                                     @RequestParam(defaultValue = "15") Integer pageSize) {

        startPage();
        if (getStoreId() != null) {
            storeId = getStoreId();
        }
        Date start = startDate != null ? DateUtils.parseDate(startDate) : DateUtils.addDays(new Date(), -7);
        Date end = endDate != null ? DateUtils.parseDate(endDate) : DateUtils.addDays(new Date(), -1);
        List<SettlementStoreStatistics> list = settlementStoreStatisticsService
                .generateStoreStatisticsByStore(storeId, start, end);

        return getDataTable(list);
    }

    /**
     * 获取门店每日交易统计列表
     */
    @PostMapping("/list/bystore/export")
    public void storeExport(@RequestParam(required = false) String startDate,
                            @RequestParam(required = false) String endDate,
                            @RequestParam(required = false) Long storeId,
                            HttpServletResponse response) {

        if (getStoreId() != null) {
            storeId = getStoreId();
        }
        Date start = startDate != null ? DateUtils.parseDate(startDate) : DateUtils.addDays(new Date(), -7);
        Date end = endDate != null ? DateUtils.parseDate(endDate) : DateUtils.addDays(new Date(), -1);
        List<SettlementStoreStatistics> list = settlementStoreStatisticsService
                .generateStoreStatisticsByStore(storeId, start, end);

        ExcelUtil<SettlementStoreStatistics> util = new ExcelUtil<>(SettlementStoreStatistics.class);
        util.exportExcel(response, list, "按门店交易统计");
    }

    /**
     * 导出门店每日交易统计
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestParam(required = false) String startDate,
                       @RequestParam(required = false) String endDate) {
        Date start = startDate != null ? DateUtils.parseDate(startDate) : DateUtils.addDays(new Date(), -14);
        Date end = endDate != null ? DateUtils.parseDate(endDate) : new Date();
        Long storeId = getLoginUser().getStoreId();

        List<SettlementStoreStatistics> list = settlementStoreStatisticsService
                .queryStoreStatisticsByDate(storeId, start, end);

        ExcelUtil<SettlementStoreStatistics> util = new ExcelUtil<>(SettlementStoreStatistics.class);
        util.exportExcel(response, list, "门店按日期交易统计");
    }
}