package com.moka.gdtauto.service.impl;

import java.time.LocalDate;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moka.gdtauto.entity.OssFileStatistics;
import com.moka.gdtauto.mapper.OssFileStatisticsMapper;
import com.moka.gdtauto.service.OssFileStatisticsService;

/**
 * <p>
 * OSS文件统计表 服务实现类
 * </p>
 *
 * @author mokamvp
 * @since 2026-03-25
 */
@Service
public class OssFileStatisticsServiceImp extends ServiceImpl<OssFileStatisticsMapper, OssFileStatistics> implements OssFileStatisticsService {

    @Override
    public Page<OssFileStatistics> listStatisticsByMd5AndDate(Long page, Long size, String fileMd5, String startDate, String endDate, String sortField, String sortOrder) {
        Page<OssFileStatistics> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<OssFileStatistics> wrapper = new LambdaQueryWrapper<>();

        // 根据fileMd5精确查询
        wrapper.eq(OssFileStatistics::getFileMd5, fileMd5);

        // 根据日期范围查询
        if (StringUtils.isNotBlank(startDate)) {
            wrapper.ge(OssFileStatistics::getDate, LocalDate.parse(startDate));
        }
        if (StringUtils.isNotBlank(endDate)) {
            wrapper.le(OssFileStatistics::getDate, LocalDate.parse(endDate));
        }

        // 处理排序
        boolean isAscending = "ascending".equalsIgnoreCase(sortOrder);
        if (StringUtils.isNotBlank(sortField)) {
            switch (sortField) {
                case "date":
                    wrapper.orderBy(true, isAscending, OssFileStatistics::getDate);
                    break;
                case "viewCount":
                    wrapper.orderBy(true, isAscending, OssFileStatistics::getViewCount);
                    break;
                case "validClickCount":
                    wrapper.orderBy(true, isAscending, OssFileStatistics::getValidClickCount);
                    break;
                case "ctr":
                    wrapper.orderBy(true, isAscending, OssFileStatistics::getCtr);
                    break;
                case "cost":
                    wrapper.orderBy(true, isAscending, OssFileStatistics::getCost);
                    break;
                default:
                    // 默认按cost降序
                    wrapper.orderByDesc(OssFileStatistics::getCost);
            }
        } else {
            // 默认按cost降序
            wrapper.orderByDesc(OssFileStatistics::getCost);
        }

        return page(pageParam, wrapper);
    }
}
