package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.*;
import shop.alien.entity.store.vo.ManagementInfoVo;
import shop.alien.entity.store.vo.SystemConfigVo;
import shop.alien.mapper.*;
import shop.alien.store.service.ManagementInfoService;
import shop.alien.store.service.StoreDictService;
import shop.alien.util.ali.AliOSSUtil;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

@Service
@RequiredArgsConstructor
public class ManagementInfoServiceImpl implements ManagementInfoService {

    @Value("${spring.web.resources.excel-path}")
    private String excelPath;

    @Value("${spring.web.resources.excel-clearing-receipt}")
    private String excelClearingReceipt;

    @Value("${spring.web.resources.excel-generate-path}")
    private String excelGeneratePath;

    @Value("${spring.web.resources.url}")
    private String fileUrl;

    private final StoreDictService storeDictService;

    private final ManagementInfoMapper managementInfoMapper;

    private final StoreIncomeDetailsRecordMapper storeIncomeDetailsRecordMapper;

    private final StoreCashOutRecordMapper storeCashOutRecordMapper;

    private final StoreInfoMapper storeInfoMapper;

    private final StoreUserMapper storeUserMapper;

    private final AliOSSUtil aliOSSUtil;

    @Override
    public IPage<ManagementInfo> getAllManagementInfo(int pageNo, int pageSize, String storeName) {
        IPage<LifeDiscountCoupon> iPage = new Page<>(pageNo, pageSize);
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 计算三天前的日期
        LocalDate threeDaysAgo = currentDate.minusDays(3);
        // 设置时间为当天的 0 点
        LocalDateTime threeDaysAgoMidnight = threeDaysAgo.atStartOfDay();
        IPage<ManagementInfo> allManagementInfo = managementInfoMapper.getAllManagementInfo(iPage, storeName);

        for (ManagementInfo managementInfo : allManagementInfo.getRecords()) {
            List<StoreIncomeDetailsRecord> storeIncomeDetailsRecords = storeIncomeDetailsRecordMapper
                    .selectList(
                            new LambdaQueryWrapper<StoreIncomeDetailsRecord>()
                                    .eq(StoreIncomeDetailsRecord::getStoreId, managementInfo.getStoreId())
                                    .gt(StoreIncomeDetailsRecord::getCreatedTime, threeDaysAgoMidnight)
                    );
            Double storeIncomeDetailsCount = 0d;
            for (StoreIncomeDetailsRecord storeIncomeDetailsRecord : storeIncomeDetailsRecords) {
                storeIncomeDetailsCount += storeIncomeDetailsRecord.getMoney();
            }
            storeIncomeDetailsCount = Math.floor(storeIncomeDetailsCount/100*100)/100;
            managementInfo.setAccountFrozen(storeIncomeDetailsCount);
        }
        return allManagementInfo;
    }

    @Override
    public HashMap<String, Object> storeBillingStatistics(String queryType) {

        int freeze = 0;
        //查询冻结配置
        SystemConfigVo systemConfigVo = storeDictService.getConfig("freeze");
        if(systemConfigVo != null){
            String freezeFlag = systemConfigVo.getConfigValue1();
            String freezeDay =  systemConfigVo.getConfigValue2();
            if(StringUtils.isNotBlank(freezeFlag) && freezeFlag.equals("1") && StringUtils.isNotBlank(freezeDay)){
                freeze = Integer.parseInt(freezeDay);
            }
        }

        HashMap<String, Object> result = new HashMap<>();

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 计算三天前的日期
        LocalDate threeDaysAgo = currentDate.minusDays(freeze);
        // 设置时间为当天的 0 点
        LocalDateTime threeDaysAgoMidnight = threeDaysAgo.atStartOfDay();

        //查询本期时间段
        String startDate = "";
        String endDate = "";
        //获取区间时间
        HashMap<String, String> stringStringHashMap = acquisitionTimeInterval(queryType, startDate, endDate);
        startDate = stringStringHashMap.get("startDate");
        endDate = stringStringHashMap.get("endDate");
        //查询账单排名
        List<ManagementInfoVo> billingRanking = managementInfoMapper.getBillingRanking(startDate, endDate);
        //查询已付款金额
        ManagementInfoVo amountPaid = managementInfoMapper.getAmountPaid(startDate, endDate, null);
        //查询总交易金额
        ManagementInfoVo totalTransactionAmount = managementInfoMapper.getTotalTransactionAmount(startDate, endDate, null);
        //查询交易笔数
        ManagementInfoVo transactionNumber = managementInfoMapper.getTransactionNumber(startDate, endDate, null);
        //查询总订单金额
        ManagementInfoVo allOrderAmount = managementInfoMapper.getAllOrderAmount(startDate, endDate, null);
        //查询总核销金额
        ManagementInfoVo allWrittenOffAmount = managementInfoMapper.getAllWrittenOffAmount(startDate, endDate, null);
        //查询总提现金额
        ManagementInfoVo totalWithdrawalAmount = managementInfoMapper.getTotalWithdrawalAmount(startDate, endDate, null);
        //查询已提现金额（根据时间查询）
        ManagementInfoVo withdrawalAmount = managementInfoMapper.getWithdrawalAmount(startDate, endDate, null);
        //查询总订单金额（根据时间查询）
        ManagementInfoVo orderAmount = managementInfoMapper.getOrderAmount(startDate, endDate, null);
        //查询总交易金额（根据时间查询）
        ManagementInfoVo transactionAmount = managementInfoMapper.getTransactionAmount(startDate, endDate, null);
        //查询总核销金额（根据时间查询）
        ManagementInfoVo writtenOffAmount = managementInfoMapper.getWrittenOffAmount(startDate, endDate, null);

        //查询已冻结金额
        LambdaQueryWrapper<StoreIncomeDetailsRecord> storeIncomeDetailsRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(freeze > 0){
            storeIncomeDetailsRecordLambdaQueryWrapper.gt(StoreIncomeDetailsRecord::getCreatedTime, threeDaysAgoMidnight);
        }
        storeIncomeDetailsRecordLambdaQueryWrapper.gt(StoreIncomeDetailsRecord::getCreatedTime, startDate);
        storeIncomeDetailsRecordLambdaQueryWrapper.lt(StoreIncomeDetailsRecord::getCreatedTime, endDate);

        List<StoreIncomeDetailsRecord> storeIncomeDetailsRecords = storeIncomeDetailsRecordMapper
                .selectList(storeIncomeDetailsRecordLambdaQueryWrapper);
        Double storeIncomeDetailsCount = 0d;
        Double storeIncomeDetailsNoCashCount = 0d;

        for (StoreIncomeDetailsRecord storeIncomeDetailsRecord : storeIncomeDetailsRecords) {
            if(storeIncomeDetailsRecord.getCashOutId() == null || storeIncomeDetailsRecord.getCashOutId() == 0){
                storeIncomeDetailsNoCashCount += storeIncomeDetailsRecord.getMoney();
            }
            storeIncomeDetailsCount += storeIncomeDetailsRecord.getMoney();
        }

        //存入账单排名
        result.put("billingRanking", billingRanking);
        //存入已付款金额
        result.put("amountPaid", amountPaid.getAmountPaid());

        //存入冻结未提现金额
        result.put("unwithdrawnAmountsFrozen", storeIncomeDetailsNoCashCount);
        //存入未解冻金额
        if(freeze == 0){
            result.put("freezeAmounts", 0);
            result.put("unwithdrawnAmountsFrozen", 0);

        } else {
            result.put("freezeAmounts", storeIncomeDetailsCount);
            result.put("unwithdrawnAmountsFrozen", storeIncomeDetailsNoCashCount);
        }
        // 已提现金额
        result.put("withdrawalAmount", withdrawalAmount.getTotalWithdrawalAmount());
        //存入未核销金额
        result.put("amountNotWrittenOff", orderAmount.getAllOrderAmount() - writtenOffAmount.getAllWrittenOffAmount());
        //存入交易笔数
        result.put("transactionNumber", transactionNumber.getTransactionNumber());
        //存入已核销金额
        result.put("amountWrittenOff", writtenOffAmount.getAllWrittenOffAmount());
        //存入总交易金额
        result.put("totalTransactionAmount", transactionAmount.getTotalTransactionAmount());
        return result;
    }

    @Override
    public IPage<ManagementInfoVo> getStoreOrderDetail(int pageNo, int pageSize, String storeId, String orderNo, String userId, String userName) {
        IPage<ManagementInfoVo> iPage = new Page<>(pageNo, pageSize);
        IPage<ManagementInfoVo> storeOrderDetail = managementInfoMapper.getStoreOrderDetail(iPage, storeId, orderNo, userId, userName);
        return storeOrderDetail;
    }

    @Override
    public IPage<ManagementInfoVo> getApplicationForWithdrawal(int pageNo, int pageSize, Integer storeId, String storeName) {
        IPage<ManagementInfoVo> iPage = new Page<>(pageNo, pageSize);
        IPage<ManagementInfoVo> storeOrderDetail = managementInfoMapper.getApplicationForWithdrawal(iPage, storeId, storeName);
        return storeOrderDetail;
    }

    @Override
    public ManagementInfoVo getCashOutDetail(Integer id) {
        return managementInfoMapper.getCashOutDetail(id);
    }

    @Override
    public HashMap<String, Object> storeDetailBillingStatistics(String storeId) {
        int freeze = 0;
        //查询冻结配置
        SystemConfigVo systemConfigVo = storeDictService.getConfig("freeze");
        if(systemConfigVo != null){
            String freezeFlag = systemConfigVo.getConfigValue1();
            String freezeDay =  systemConfigVo.getConfigValue2();
            if(StringUtils.isNotBlank(freezeFlag) && freezeFlag.equals("1") && StringUtils.isNotBlank(freezeDay)){
                freeze = Integer.parseInt(freezeDay);
            }
        }

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 计算三天前的日期
        LocalDate threeDaysAgo = currentDate.minusDays(freeze);
        // 设置时间为当天的 0 点
        LocalDateTime threeDaysAgoMidnight = threeDaysAgo.atStartOfDay();

        HashMap<String, Object> result = new HashMap<>();
        //查询总交易金额
        ManagementInfoVo allOrderAmount = managementInfoMapper.getAllOrderAmount(null, null, storeId);
        //查询交易用户数
        ManagementInfoVo userCount = managementInfoMapper.getUserCount(storeId);
        //查询交易笔数
        ManagementInfoVo orderTransactionNumber = managementInfoMapper.getOrderTransactionNumber(storeId);
        //查询核验金额
        ManagementInfoVo verificationAmount = managementInfoMapper.getVerificationAmount(storeId);

        //查询已提现金额
        ManagementInfoVo totalWithdrawalAmount = managementInfoMapper.getTotalWithdrawalAmount(null, null, storeId);

        //查询冻结金额
        List<StoreIncomeDetailsRecord> storeIncomeDetailsRecords = storeIncomeDetailsRecordMapper
                .selectList(
                        new LambdaQueryWrapper<StoreIncomeDetailsRecord>()
                                .gt(StoreIncomeDetailsRecord::getCreatedTime, threeDaysAgoMidnight)
                                .eq(StoreIncomeDetailsRecord::getStoreId, storeId)
                );
        Double storeIncomeDetailsCount = 0d;
        Double storeIncomeDetailsNoCashCount = 0d;

        for (StoreIncomeDetailsRecord storeIncomeDetailsRecord : storeIncomeDetailsRecords) {
            if(storeIncomeDetailsRecord.getCashOutId() == null || storeIncomeDetailsRecord.getCashOutId() == 0){
                storeIncomeDetailsNoCashCount += storeIncomeDetailsRecord.getMoney();
            }
            storeIncomeDetailsCount += storeIncomeDetailsRecord.getMoney();
        }

        //存入已付款金额
        result.put("allOrderAmount", allOrderAmount.getAllOrderAmount());
        //存入总交易金额
        result.put("userCount", userCount.getUserCount());
        //存入交易笔数
        result.put("orderTransactionNumber", orderTransactionNumber.getOrderTransactionNumber());
        //存入核验金额
        result.put("verificationAmount", verificationAmount.getVerificationAmount());
        //已提现金额
        result.put("totalWithdrawalAmount", totalWithdrawalAmount.getTotalWithdrawalAmount());

        //冻结金额
        if(freeze == 0){
            //冻结金额
            result.put("freezeAmounts", 0);
            //冻结待提现金额
            result.put("unwithdrawnAmountsFrozen", 0);
        } else {
            //冻结金额
            result.put("freezeAmounts", storeIncomeDetailsCount);
            //冻结待提现金额
            result.put("unwithdrawnAmountsFrozen", storeIncomeDetailsNoCashCount);

        }
        return result;
    }

    @Override
    public HashMap<String, Object> generateClearingReceipt(String cashId) {

        HashMap<String, Object> result = new HashMap<>();
        StoreCashOutRecord storeCashOutRecord = storeCashOutRecordMapper.selectById(cashId);
        StoreInfo storeInfo = storeInfoMapper.selectById(storeCashOutRecord.getStoreId());
        StoreUser storeUser = storeUserMapper.selectOne(new LambdaQueryWrapper<StoreUser>().eq(StoreUser::getStoreId, storeInfo.getId()));

        // 创建 DateFormat 对象
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        // 将 Date 对象转换为字符串
        String dateText = df.format(storeCashOutRecord.getPaymentDate());
        double doubleMoney = (double) storeCashOutRecord.getMoney() / 100;
        String moneyText = doubleMoney + "";
        String fileName = "storeCashOutRecord" + storeCashOutRecord.getId();
        String filePath = generateReceiptFile(storeInfo.getStoreName(), storeUser.getId().toString(), storeUser.getPhone(), moneyText, moneyText, dateText, fileName);
        result.put("filePath", filePath);
        return result;
    }

    @Override
    public HashMap<String, Object> getBasicStatistics() {
        HashMap<String, Object> result = new HashMap<>();
        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        // 设置时间为当天的 0 点
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        // 获取 0 点的 Date 对象
        Date midnight = calendar.getTime();
        // 定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 格式化日期
        String formattedDate = sdf.format(midnight);
        //获取今日平台净利润
        ManagementInfoVo platformNetProfit = managementInfoMapper.getPlatformNetProfit(formattedDate);
        //存入今日平台净利润
        result.put("netProfitTodayPlatform", platformNetProfit.getProfit());
        //获取总计平台净利润
        ManagementInfoVo platformNetProfitAll = managementInfoMapper.getPlatformNetProfit(null);
        //存入总计平台净利润
        result.put("netProfitTodayPlatformAll", platformNetProfitAll.getProfit());
        //获取今日订单量
        ManagementInfoVo orderQuantity = managementInfoMapper.getOrderQuantity(formattedDate);
        //存入今日订单量
        result.put("orderQuantityToday", orderQuantity.getCount());
        //获取总订单量
        ManagementInfoVo orderQuantityAll = managementInfoMapper.getOrderQuantity(null);
        //存入总订单量
        result.put("orderQuantityAll", orderQuantityAll.getCount());
        //获取今日成交金额
        ManagementInfoVo tradingVolume = managementInfoMapper.getTradingVolume(formattedDate);
        //存入今日成交金额
        result.put("tradingVolume", tradingVolume.getProfit());
        //获取总成交金额
        ManagementInfoVo tradingVolumeAll = managementInfoMapper.getTradingVolume(null);
        //存入总成交金额
        result.put("tradingVolumeAll", tradingVolumeAll.getProfit());
        //查询今日退款订单量
        ManagementInfoVo refundOrderQuantity = managementInfoMapper.getRefundOrderQuantity(formattedDate);
        //存入今日退款订单量
        result.put("refundOrderQuantity", refundOrderQuantity.getCount());
        //查询总退款订单量
        ManagementInfoVo refundOrderQuantityAll = managementInfoMapper.getRefundOrderQuantity(null);
        //存入总退款订单量
        result.put("refundOrderQuantityAll", refundOrderQuantityAll.getCount());
        //查询今日总订单量
        ManagementInfoVo totalOrderVolume = managementInfoMapper.getTotalOrderVolume(formattedDate);
        //存入今日总订单量
        result.put("totalOrderVolume", totalOrderVolume.getCount());
        //查询平台总订单量
        ManagementInfoVo totalOrderVolumeAll = managementInfoMapper.getTotalOrderVolume(null);
        //存入平台总订单量
        result.put("totalOrderVolumeAll", totalOrderVolumeAll.getCount());
        //查询今日退款金额
        ManagementInfoVo refundAmount = managementInfoMapper.getRefundAmount(formattedDate);
        //存入今日退款金额
        result.put("refundAmount", refundAmount.getProfit());
        //查询平台总退款金额
        ManagementInfoVo refundAmountAll = managementInfoMapper.getRefundAmount(null);
        //存入平台总退款金额
        result.put("refundAmountAll", refundAmountAll.getProfit());

        return result;
    }

    @Override
    public List<ManagementInfoVo> getQueryNetProfit(Integer type) {
        List<ManagementInfoVo> result = new ArrayList<>();
        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        // 设置时间为当天的 0 点
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        // 获取 0 点的 Date 对象
        Date midnight = calendar.getTime();
        // 定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 格式化日期
        String formattedDate = sdf.format(midnight);
        if (type == 0) {//如果查询的是日
            result = managementInfoMapper.getQueryNetProfitDay(formattedDate);
        } else if (type == 1) {//如果查询的是周
            result = managementInfoMapper.getQueryNetProfitWeek(formattedDate);
        } else if (type == 2) {//如果查询的是月
            result = managementInfoMapper.getQueryNetProfitMonth(formattedDate);
        } else if (type == 3) {//如果查询的年
            result = managementInfoMapper.getQueryNetProfitYear(formattedDate);
        }
        return result;
    }

    @Override
    public List<ManagementInfoVo> getTradingVolume(Integer type) {

        List<ManagementInfoVo> result = new ArrayList<>();
        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        // 设置时间为当天的 0 点
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        // 获取 0 点的 Date 对象
        Date midnight = calendar.getTime();
        // 定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 格式化日期
        String formattedDate = sdf.format(midnight);
        if (type == 0) {//如果查询的是日
            result = managementInfoMapper.getTradingVolumeDay(formattedDate);
        } else if (type == 1) {//如果查询的是周
            result = managementInfoMapper.getTradingVolumeWeek(formattedDate);
        } else if (type == 2) {//如果查询的是月
            result = managementInfoMapper.getTradingVolumeMonth(formattedDate);
        } else if (type == 3) {//如果查询的年
            result = managementInfoMapper.getTradingVolumeYear(formattedDate);
        }
        return result;
    }

    @Override
    public List<ManagementInfoVo> getOrderQuantity(Integer type) {
        List<ManagementInfoVo> result = new ArrayList<>();
        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        // 设置时间为当天的 0 点
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        // 获取 0 点的 Date 对象
        Date midnight = calendar.getTime();
        // 定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 格式化日期
        String formattedDate = sdf.format(midnight);
        if (type == 0) {//如果查询的是日
            result = managementInfoMapper.getOrderQuantityDay(formattedDate);
        } else if (type == 1) {//如果查询的是周
            result = managementInfoMapper.getOrderQuantityWeek(formattedDate);
        } else if (type == 2) {//如果查询的是月
            result = managementInfoMapper.getOrderQuantityMonth(formattedDate);
        } else if (type == 3) {//如果查询的年
            Instant firstDayOfYear = LocalDate.now()
                    .withMonth(1)
                    .withDayOfMonth(1)
                    .atStartOfDay(ZoneId.systemDefault())
                    .toInstant();
            formattedDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                    .withZone(ZoneId.systemDefault())
                    .format(firstDayOfYear);
            result = managementInfoMapper.getOrderQuantityYear(formattedDate);
        }
        return result;
    }

    @Override
    public List<ManagementInfoVo> getSalesVolume(Integer type) {
        LocalDate now = LocalDate.now();
        LocalDateTime startDate, endDate;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        switch (type) {
            case 0:
                // 如果查询的是日
                startDate = LocalDateTime.of(now, LocalTime.MIN);
                endDate = LocalDateTime.of(now.plusDays(1), LocalTime.MIN);
                break;
            case 1:
                // 如果查询的是周
                LocalDate monday = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
                startDate = LocalDateTime.of(monday, LocalTime.MIN);
                endDate = LocalDateTime.of(monday.plusWeeks(1), LocalTime.MIN);
                break;
            case 2:
                // 如果查询的是月
                startDate = LocalDateTime.of(now.with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN);
                endDate = LocalDateTime.of(now.with(TemporalAdjusters.firstDayOfNextMonth()), LocalTime.MIN);
                break;
            case 3:
                // 如果查询的是年
                startDate = LocalDateTime.of(now.with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN);
                endDate = LocalDateTime.of(now.with(TemporalAdjusters.firstDayOfNextYear()), LocalTime.MIN);
                break;
            default:
                throw new IllegalArgumentException("不支持的类型: " + type);
        }
        String startDateFormat = formatter.format(startDate);
        String endDateFormat = formatter.format(endDate);
        List<ManagementInfoVo> salesVolume = managementInfoMapper.getSalesVolume(startDateFormat, endDateFormat);
        int rowNum = 1;
        for (ManagementInfoVo managementInfoVo : salesVolume) {
            managementInfoVo.setRowNum(rowNum + "");
            rowNum++;
        }
        return salesVolume;
    }

    @Override
    public IPage<ManagementInfoVo> getStorePlatformProfitDetails(Integer pageNum, Integer pageSize, String storeId, String type, String startTime, String entTime, String storeName) {
        IPage<ManagementInfoVo> cardPage = new Page<>(pageNum, pageSize);
        IPage<ManagementInfoVo> storePlatformProfitDetails = new Page<>();
        if ("1".equals(type)) {
            //如果 type 是 当日
            // 获取当日零点时间
            LocalDateTime todayMidnight = LocalDate.now().atStartOfDay();
            // 定义日期时间格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // 将当日零点时间转换为字符串
            String midnightString = todayMidnight.format(formatter);
            storePlatformProfitDetails = managementInfoMapper.getStorePlatformProfitDetails(cardPage, midnightString, null, storeId, storeName);
        } else if ("2".equals(type)) {
            //如果 type 是所有
            storePlatformProfitDetails = managementInfoMapper.getStorePlatformProfitDetails(cardPage, startTime, entTime, storeId, storeName);
        }
        return storePlatformProfitDetails;
    }

    @Override
    public IPage<ManagementInfoVo> getStorePlatformOrderVolume(Integer pageNum, Integer pageSize, String orderId, String type, String orderType, String startTime, String entTime, String couponName, String couponType, String storeName) {
        IPage<ManagementInfoVo> cardPage = new Page<>(pageNum, pageSize);
        IPage<ManagementInfoVo> storePlatformProfitDetails = new Page<>();

        String orderTypeQuery = "";
        if ("0".equals(orderType)) {
            //待付款
            orderTypeQuery = "0";
        } else if ("4".equals(orderType)) {
            //已取消
            orderTypeQuery = "4";
        } else if ("1".equals(orderType)) {
            // 待使用
            orderTypeQuery = "1";
        } else if ("7".equals(orderType)) {
            // 已完成
            orderTypeQuery = "7";
        } else if ("5".equals(orderType)) {
            // 已退款
            orderTypeQuery = "5";
        }

        if ("3".equals(type) || "5".equals(type)) {
            //如果 type 是 当日
            // 获取当日零点时间
            LocalDateTime todayMidnight = LocalDate.now().atStartOfDay();
            // 定义日期时间格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // 将当日零点时间转换为字符串
            String midnightString = todayMidnight.format(formatter);
            storePlatformProfitDetails = managementInfoMapper.getStorePlatformOrderVolume(cardPage, midnightString, null, orderId, orderTypeQuery, couponName, couponType, storeName);
        } else if ("4".equals(type) || "6".equals(type)) {
            //如果 type 是所有
            storePlatformProfitDetails = managementInfoMapper.getStorePlatformOrderVolume(cardPage, startTime, entTime, orderId, orderTypeQuery, couponName, couponType, storeName);
        }
        return storePlatformProfitDetails;
    }

    public HashMap<String, String> acquisitionTimeInterval(String queryType, String startDate, String endDate) {
        HashMap<String, String> result = new HashMap<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (queryType.equals("year")) {
            // 获取本年第一天零点 0 分 0 秒
            LocalDate currentDate = LocalDate.now();
            LocalDate firstDayOfYear = currentDate.with(TemporalAdjusters.firstDayOfYear());
            LocalDateTime startOfYear = firstDayOfYear.atStartOfDay();
            // 获取本年最后一天 23:59:59
            LocalDate lastDayOfYear = currentDate.with(TemporalAdjusters.lastDayOfYear());
            LocalDateTime endOfYear = lastDayOfYear.atTime(LocalTime.MAX);
            String formattedStartOfYear = startOfYear.format(formatter);
            String formattedEndOfYear = endOfYear.format(formatter);

            startDate = formattedStartOfYear;
            endDate = formattedEndOfYear;
        } else if (queryType.equals("month")) {
            // 获取本月第一天零点 0 分 0 秒
            LocalDate currentDate = LocalDate.now();
            LocalDate firstDayOfMonth = currentDate.with(TemporalAdjusters.firstDayOfMonth());
            LocalDateTime startOfMonth = firstDayOfMonth.atStartOfDay();
            // 获取本月最后一天 23:59:59
            LocalDate lastDayOfMonth = currentDate.with(TemporalAdjusters.lastDayOfMonth());
            LocalDateTime endOfMonth = lastDayOfMonth.atTime(LocalTime.MAX);
            String formattedStartOfMonth = startOfMonth.format(formatter);
            String formattedEndOfMonth = endOfMonth.format(formatter);

            startDate = formattedStartOfMonth;
            endDate = formattedEndOfMonth;
        } else if (queryType.equals("week")) {
            // 获取本周第一天零点 0 分 0 秒，这里假设周一为一周的第一天
            LocalDate currentDate = LocalDate.now();
            LocalDate firstDayOfWeek = currentDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
            LocalDateTime startOfWeek = firstDayOfWeek.atStartOfDay();
            // 获取本周最后一天 23:59:59，这里假设周日为一周的最后一天
            LocalDate lastDayOfWeek = currentDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
            LocalDateTime endOfWeek = lastDayOfWeek.atTime(LocalTime.MAX);
            String formattedStartOfWeek = startOfWeek.format(formatter);
            String formattedEndOfWeek = endOfWeek.format(formatter);

            startDate = formattedStartOfWeek;
            endDate = formattedEndOfWeek;
        }
        result.put("startDate", startDate);
        result.put("endDate", endDate);
        return result;
    }

    public String generateReceiptFile(String storeName, String storeAccount, String storePhone, String invoiceAmount, String amountPaid, String paymentTime, String fileName) {
        String filePath = excelPath + excelGeneratePath + fileName + ".xlsx";
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("win")) {
            filePath = "d:/" + filePath;
            String substring = filePath.substring(0, filePath.lastIndexOf("/"));
            File dir = new File(substring);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }
        // 创建 File 对象
        File file = new File(excelPath + excelGeneratePath + fileName + ".xlsx");
        // 判断文件是否存在
        if (file.exists()) {
            filePath = fileUrl + "excel" + excelGeneratePath + fileName + ".xlsx";
            return filePath;
        }
        String templateUrl = fileUrl +"excel/" +excelClearingReceipt;
        try (FileInputStream fis = toFileInputStream(downloadAsInputStream(templateUrl));
             Workbook workbook = new XSSFWorkbook(fis)) {
            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);

            //获取第三行
            Row rowThree = sheet.getRow(2);
            if (rowThree == null) {
                rowThree = sheet.createRow(2);
            }
            // 获取第二列（索引为 1）的单元格，若不存在则创建 商家名称单元格
            Cell cellStoreName = rowThree.getCell(1);
            if (cellStoreName == null) {
                cellStoreName = rowThree.createCell(1);
            }
            // 向单元格写入数据
            cellStoreName.setCellValue(storeName);

            // 获取第二列（索引为 3）的单元格，若不存在则创建 商家账号单元格
            Cell cellStoreAccount = rowThree.getCell(3);
            if (cellStoreAccount == null) {
                cellStoreAccount = rowThree.createCell(3);
            }
            // 向单元格写入数据
            cellStoreAccount.setCellValue(storeAccount);


            // 获取第二列（索引为 5）的单元格，若不存在则创建 联系方式单元格
            Cell cellStorePhone = rowThree.getCell(5);
            if (cellStorePhone == null) {
                cellStorePhone = rowThree.createCell(5);
            }
            // 向单元格写入数据
            cellStorePhone.setCellValue(storePhone);

            //获取第七行
            Row rowSeven = sheet.getRow(6);
            if (rowSeven == null) {
                rowSeven = sheet.createRow(6);
            }

            // 获取第一列（索引为 0）的单元格，若不存在则创建 账单金额单元格
            Cell cellInvoiceAmount = rowSeven.getCell(0);
            if (cellInvoiceAmount == null) {
                cellInvoiceAmount = rowSeven.createCell(0);
            }
            // 向单元格写入数据
            cellInvoiceAmount.setCellValue(invoiceAmount);
            // 获取第二列（索引为 2）的单元格，若不存在则创建 账单金额单元格
            Cell cellAmountPaid = rowSeven.getCell(2);
            if (cellAmountPaid == null) {
                cellAmountPaid = rowSeven.createCell(2);
            }
            // 向单元格写入数据
            cellAmountPaid.setCellValue(amountPaid);
            // 获取第三列（索引为 4）的单元格，若不存在则创建 账单金额单元格
            Cell cellPaymentTime = rowSeven.getCell(4);
            if (cellPaymentTime == null) {
                cellPaymentTime = rowSeven.createCell(4);
            }
            // 向单元格写入数据
            cellPaymentTime.setCellValue(paymentTime);

            // 自动调整列宽
            for (int i = 0; i < sheet.getRow(0).getLastCellNum(); i++) {
                sheet.autoSizeColumn(i);
            }
            // 保存填充后的工作簿到本地文件
//            try (FileOutputStream fos = new FileOutputStream(excelPath + excelGeneratePath + fileName + ".xlsx")) {
//                workbook.write(fos);
//                filePath = fileUrl + "excel" + excelGeneratePath + fileName + ".xlsx";
//            }
            try (FileOutputStream fos = new FileOutputStream(filePath)) {
                workbook.write(fos);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return aliOSSUtil.uploadFile(new File(filePath), "excel/" + fileName + ".xlsx");
    }

    public InputStream downloadAsInputStream(String fileUrl) throws IOException {
        URL url = new URL(fileUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        return connection.getInputStream(); // 直接返回 HTTP 流
    }
    public static FileInputStream toFileInputStream(InputStream inputStream) throws IOException {
        Path tempFile = Files.createTempFile("temp-", ".tmp");
        tempFile.toFile().deleteOnExit();
        try (InputStream is = inputStream) {
            Files.copy(is, tempFile, StandardCopyOption.REPLACE_EXISTING);
        }
        return new FileInputStream(tempFile.toFile());
    }
    public FileInputStream getExcelTemplate() throws IOException {
        // 1. 通过 ClassPathResource 获取文件
        ClassPathResource resource = new ClassPathResource("templates/clearing_receipt.xlsx");
        // 2. 转换为 FileInputStream（仅在文件系统有效，JAR 内会报错）
        File file = resource.getFile(); // 注意：JAR 中会抛出 FileNotFoundException
        return new FileInputStream(file);
    }

//    public static void main(String[] args) {
//            try (FileInputStream fis = new FileInputStream("D:\\excel\\clearing_receipt.xlsx");
//                 Workbook workbook = new XSSFWorkbook(fis)) {
//
//                // 获取第一个工作表
//                Sheet sheet = workbook.getSheetAt(0);
//
//                //商家名称
//                String storeName = "胜道烤肉";
//                //商家账号
//                String storeAccount = "店铺账号";
//                //联系方式
//                String storePhone = "商店联系方式";
//                //账单金额
//                String invoiceAmount = "11000";
//                //已付金额
//                String amountPaid = "12000";
//                //付款时间
//                String paymentTime = "2025-03-18";
//
//                //获取第三行
//                Row rowThree = sheet.getRow(2);
//                if (rowThree == null) {
//                    rowThree = sheet.createRow(2);
//                }
//                // 获取第二列（索引为 1）的单元格，若不存在则创建 商家名称单元格
//                Cell cellStoreName = rowThree.getCell(1);
//                if (cellStoreName == null) {
//                    cellStoreName = rowThree.createCell(1);
//                }
//                // 向单元格写入数据
//                cellStoreName.setCellValue(storeName);
//
//                // 获取第二列（索引为 3）的单元格，若不存在则创建 商家账号单元格
//                Cell cellStoreAccount = rowThree.getCell(3);
//                if (cellStoreAccount == null) {
//                    cellStoreAccount = rowThree.createCell(3);
//                }
//                // 向单元格写入数据
//                cellStoreAccount.setCellValue(storeAccount);
//
//
//                // 获取第二列（索引为 5）的单元格，若不存在则创建 联系方式单元格
//                Cell cellStorePhone = rowThree.getCell(5);
//                if (cellStorePhone == null) {
//                    cellStorePhone = rowThree.createCell(5);
//                }
//                // 向单元格写入数据
//                cellStorePhone.setCellValue(storePhone);
//
//                //获取第七行
//                Row rowSeven = sheet.getRow(6);
//                if (rowSeven == null) {
//                    rowSeven = sheet.createRow(6);
//                }
//
//                // 获取第一列（索引为 0）的单元格，若不存在则创建 账单金额单元格
//                Cell cellInvoiceAmount = rowSeven.getCell(0);
//                if (cellInvoiceAmount == null) {
//                    cellInvoiceAmount = rowSeven.createCell(0);
//                }
//                // 向单元格写入数据
//                cellInvoiceAmount.setCellValue(invoiceAmount);
//                // 获取第二列（索引为 2）的单元格，若不存在则创建 账单金额单元格
//                Cell cellAmountPaid = rowSeven.getCell(2);
//                if (cellAmountPaid == null) {
//                    cellAmountPaid = rowSeven.createCell(2);
//                }
//                // 向单元格写入数据
//                cellAmountPaid.setCellValue(amountPaid);
//                // 获取第三列（索引为 4）的单元格，若不存在则创建 账单金额单元格
//                Cell cellPaymentTime = rowSeven.getCell(4);
//                if (cellPaymentTime == null) {
//                    cellPaymentTime = rowSeven.createCell(4);
//                }
//                // 向单元格写入数据
//                cellPaymentTime.setCellValue(paymentTime);
//
//                // 自动调整列宽
//                for (int i = 0; i < sheet.getRow(0).getLastCellNum(); i++) {
//                    sheet.autoSizeColumn(i);
//                }
//                // 保存填充后的工作簿到本地文件
//                try (FileOutputStream fos = new FileOutputStream("D:\\excel\\file\\filled_template.xlsx")) {
//                    workbook.write(fos);
//                    System.out.println("Excel 文件填充并保存成功，文件路径：filled_template.xlsx");
//                }
//
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//    }

//    public static void main(String[] args) {
//        try (FileInputStream fis = new FileInputStream("D:\\excel\\clearing_receipt2.xlsx");
//             Workbook workbook = new XSSFWorkbook(fis)) {
//
//            // 获取第一个工作表
//            Sheet sheet = workbook.getSheetAt(0);
//
//            // 获取工作表的总行数
//            int lastRowNum = sheet.getLastRowNum();
//            for (int i = 0; i <= lastRowNum; i++) {
//                Row row = sheet.getRow(i);
//                if (row != null) {
//                    // 获取当前行的最后一个单元格的索引
//                    int lastCellNum = row.getLastCellNum();
//                    for (int j = 0; j < lastCellNum; j++) {
//                        Cell cell = row.getCell(j);
//                        if (cell != null) {
//                            System.err.println("row" + i + ",cell" + j);
//                            System.err.println(cell);
//                        }
//                        if (cell != null) {
//                            // 根据单元格的类型获取其值
//                            switch (cell.getCellType()) {
//                                case STRING:
//                                    System.out.print(cell.getStringCellValue() + "\t");
//                                    break;
//                                case NUMERIC:
//                                    if (DateUtil.isCellDateFormatted(cell)) {
//                                        System.out.print(cell.getDateCellValue() + "\t");
//                                    } else {
//                                        System.out.print(cell.getNumericCellValue() + "\t");
//                                    }
//                                    break;
//                                case BOOLEAN:
//                                    System.out.print(cell.getBooleanCellValue() + "\t");
//                                    break;
//                                case FORMULA:
//                                    System.out.print(cell.getCellFormula() + "\t");
//                                    break;
//                                default:
//                                    System.out.print("\t");
//                            }
//                        } else {
//                            System.out.print("\t");
//                        }
//                    }
//                }
//                System.out.println();
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

}