/*
 * Copyright (c) 2021, orioc and/or its affiliates. All rights reserved.
 * Use, Copy is subject to authorized license.
 */
package com.bonus.sharedstation.web.service.impl;

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.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.sharedstation.app.dto.RepairServiceOrderDTO;
import com.bonus.sharedstation.app.entity.RepairService;
import com.bonus.sharedstation.app.entity.RepairServiceOrder;
import com.bonus.sharedstation.app.mapper.RepairServiceMapper;
import com.bonus.sharedstation.app.mapper.RepairServiceOrderMapper;
import com.bonus.sharedstation.common.Constant.Constant;
import com.bonus.sharedstation.web.service.IRepairServiceWebService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * Service实现
 *
 * @author hyq
 * @date 2024-03-15
 */
@Service
@Transactional(readOnly = true)
@Slf4j
public class RepairServiceWebServiceImpl extends ServiceImpl<RepairServiceMapper, RepairService> implements IRepairServiceWebService
{


    @Resource
    private RepairServiceOrderMapper repairServiceOrderMapper;

    /**
     * 分页查询订单web
     * @param dto
     * @return
     */
    @Override
    public AjaxResult getListWeb(RepairServiceOrderDTO dto) {
        log.info("查询 入参: {}", dto);
        LambdaQueryWrapper<RepairServiceOrder> queryWrapper = new LambdaQueryWrapper<>();
        // 创建分页对象
        Page<RepairServiceOrder> page = new Page<>(dto.getCurrentPage(), dto.getLimit());
        if (StringUtils.isNotEmpty(dto.getName())) {
            queryWrapper.like(RepairServiceOrder::getName, dto.getName());
        }
        queryWrapper
                .eq(RepairServiceOrder::getIsDeleted, dto.getIsDeleted())
                .orderByDesc(RepairServiceOrder::getCreatedTime);     // 降序排序
        if (StringUtils.isNotEmpty(dto.getTimeType())) {
            switch (dto.getTimeType()) {
                case Constant.CUTHOTIMS_TIME://自定义时间
                    return listByCustomDateRange(page, dto.getBeginTime(), dto.getEndTime(), dto);
                case Constant.MNONTH_TIME://月2024-12
                    return listByMonth(page, dto.getYearMonth(),dto);
                case Constant.QUARTER_TIME://季度
                    return listByQuarter(page, dto.getYear(), dto.getQuarter(),dto);
                case Constant.YEAR_TIME://年
                    return listByYear(page, dto.getYear(),dto);
                default:
                    break;
            }
        }
        Page<RepairServiceOrder> result = repairServiceOrderMapper.selectPage(page, queryWrapper);
        //处理参数问题
        return AjaxResult.success(result);
    }

    // 将 LocalDateTime 转换为 Date
    private Date toUtilDate(LocalDateTime localDateTime) {
        return java.sql.Timestamp.valueOf(localDateTime);
    }


    // 按自定义时间段查询订单列表
    public AjaxResult listByCustomDateRange(Page<RepairServiceOrder> page, Date startDate, Date endDate, RepairServiceOrderDTO dto) {
        LambdaQueryWrapper<RepairServiceOrder> queryWrapper = buildDateRangeQuery(startDate, endDate,dto);

        Page<RepairServiceOrder> result = repairServiceOrderMapper.selectPage(page, queryWrapper);

        return AjaxResult.success(result);

    }

    // 构建日期范围查询条件
    private LambdaQueryWrapper<RepairServiceOrder> buildDateRangeQuery(Date startTime, Date endTime,RepairServiceOrderDTO dto) {
        LambdaQueryWrapper<RepairServiceOrder> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(dto.getName())) {
            queryWrapper.like(RepairServiceOrder::getName, dto.getName());
        }
        queryWrapper.eq(RepairServiceOrder::getIsDeleted, "0")
                .orderByDesc(RepairServiceOrder::getCreatedTime);     // 降序排序; // 只查询未删除的记录
        queryWrapper.between(RepairServiceOrder::getOrderTime, startTime, endTime);
        return queryWrapper;
    }


    // 按月查询订单列表
    public AjaxResult listByMonth(Page<RepairServiceOrder> page, String yearMonth,RepairServiceOrderDTO dto) {
        //格式为2024-12
        LocalDate startOfMonth = LocalDate.parse(yearMonth + "-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate endOfMonth = startOfMonth.withDayOfMonth(startOfMonth.lengthOfMonth());

        LambdaQueryWrapper<RepairServiceOrder> queryWrapper = buildDateRangeQuery(
                toUtilDate(startOfMonth.atStartOfDay()),
                toUtilDate(endOfMonth.atTime(23, 59, 59)),dto
        );


        Page<RepairServiceOrder> result = repairServiceOrderMapper.selectPage(page, queryWrapper);
        //处理参数问题
        return AjaxResult.success(result);
    }

    // 按季度查询订单列表
    public AjaxResult listByQuarter(Page<RepairServiceOrder> page, Integer year, Integer quarter,RepairServiceOrderDTO dto) {
//        LocalDate startOfQuarter = LocalDate.of(year, (quarter - 1) * 3 + 1, 1);
//        LocalDate endOfQuarter = startOfQuarter.plusMonths(2).withDayOfMonth(startOfQuarter.getMonth().length(false));


        LocalDate startOfQuarter = LocalDate.of(year, (quarter - 1) * 3 + 1, 1);
        int lastMonthOfQuarter = ((quarter - 1) * 3 + 3) % 12 + 1;
        YearMonth yearMonth = YearMonth.of(year, lastMonthOfQuarter);
        int daysInLastMonth = yearMonth.lengthOfMonth();
        LocalDate endOfQuarter = LocalDate.of(year, lastMonthOfQuarter, daysInLastMonth);

        LambdaQueryWrapper<RepairServiceOrder> queryWrapper = buildDateRangeQuery(
                toUtilDate(startOfQuarter.atStartOfDay()),
                toUtilDate(endOfQuarter.atTime(23, 59, 59)),dto
        );

        Page<RepairServiceOrder> result = repairServiceOrderMapper.selectPage(page, queryWrapper);
        //处理参数问题
        return AjaxResult.success(result);
    }

    // 按年查询订单列表
    public AjaxResult listByYear(Page<RepairServiceOrder> page, Integer year,RepairServiceOrderDTO dto) {
        LocalDate startOfYear = LocalDate.of(year, 1, 1);
        LocalDate endOfYear = LocalDate.of(year, 12, 31);

        LambdaQueryWrapper<RepairServiceOrder> queryWrapper = buildDateRangeQuery(
                toUtilDate(startOfYear.atStartOfDay()),
                toUtilDate(endOfYear.atTime(23, 59, 59)),dto
        );

        Page<RepairServiceOrder> result = repairServiceOrderMapper.selectPage(page, queryWrapper);
        //处理参数问题
        return AjaxResult.success(result);
    }


}
