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.GreenOrderDTO;
import com.bonus.sharedstation.app.entity.GreenInfo;
import com.bonus.sharedstation.app.entity.GreenOrder;
import com.bonus.sharedstation.app.entity.GreenOrderInfo;
import com.bonus.sharedstation.app.mapper.GreenInfoMapper;
import com.bonus.sharedstation.app.mapper.GreenOrderInfoMapper;
import com.bonus.sharedstation.app.mapper.GreenOrderMapper;
import com.bonus.sharedstation.common.Constant.Constant;
import com.bonus.sharedstation.web.service.IGreenInfoWebService;
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;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Service实现
 *
 * @author hyq
 * @date 2024-03-15
 */
@Service
@Transactional(readOnly = true)
@Slf4j
public class GreenInfoWebServiceImpl extends ServiceImpl<GreenInfoMapper, GreenInfo> implements IGreenInfoWebService {


    @Resource
    private GreenOrderMapper greenOrderMapper;
    @Resource
    private GreenOrderInfoMapper greenOrderInfoMapper;


    /**
     * 绿植订单 分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public AjaxResult getListWeb(GreenOrderDTO dto) {
        log.info("查询分页入参: {}", dto);
        LambdaQueryWrapper<GreenOrder> queryWrapper = new LambdaQueryWrapper<>();
        // 创建分页对象
        Page<GreenOrder> page = new Page<>(dto.getCurrentPage(), dto.getLimit());

        if (StringUtils.isNotEmpty(dto.getName())) {
            queryWrapper.like(GreenOrder::getName, dto.getName());
        }
        queryWrapper
                .eq(GreenOrder::getIsDeleted, dto.getIsDeleted())
                .orderByDesc(GreenOrder::getCreatedTime);
        if (StringUtils.isNotEmpty(dto.getTimeType())) {
            switch (dto.getTimeType()) {
                //自定义时间
                case Constant.CUTHOTIMS_TIME:
                    return listByCustomDateRange(page, dto.getBeginTime(), dto.getEndTime(), dto);
                // 月份2024-12
                case Constant.MNONTH_TIME:
                    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<GreenOrder> result = greenOrderMapper.selectPage(page, queryWrapper);
        return changeParam(result);
    }

    /**
     * 处理参数问题
     *
     * @param
     * @return
     */
    public AjaxResult changeParam(Page<GreenOrder> result) {
        //处理参数问题
        List<GreenOrder> records = result.getRecords();
        if (records == null) {
            return AjaxResult.success(result);
        }
        //查询所有的绿植订单信息
        LambdaQueryWrapper<GreenOrderInfo> greenOrderInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        greenOrderInfoLambdaQueryWrapper
                .eq(GreenOrderInfo::getIsDeleted, "0")
                .orderByDesc(GreenOrderInfo::getCreatedTime);
        List<GreenOrderInfo> greenOrderInfos = greenOrderInfoMapper.selectList(greenOrderInfoLambdaQueryWrapper);
        for (GreenOrder record : records) {
            if (record != null) {
                Integer id = record.getId();
                List<GreenOrderInfo> collect = greenOrderInfos.stream().
                        filter(greenOrderInfo -> greenOrderInfo.getOrderId() != null
                                && greenOrderInfo.getOrderId() == id).collect(Collectors.toList());
                if (collect != null) {
                    record.setGreenOrderInfoList(collect);
                }
            }
        }

        return AjaxResult.success(result);
    }


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

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

        Page<GreenOrder> result = greenOrderMapper.selectPage(page, queryWrapper);
        return changeParam(result);

    }

    // 构建日期范围查询条件
    private LambdaQueryWrapper<GreenOrder> buildDateRangeQuery(Date startTime, Date endTime, GreenOrderDTO dto) {
        LambdaQueryWrapper<GreenOrder> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(dto.getName())) {
            queryWrapper.like(GreenOrder::getName, dto.getName());
        }
        queryWrapper.eq(GreenOrder::getIsDeleted, "0")
                .orderByDesc(GreenOrder::getCreatedTime);
        queryWrapper.between(GreenOrder::getOrderTime, startTime, endTime);
        return queryWrapper;
    }

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

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


        Page<GreenOrder> result = greenOrderMapper.selectPage(page, queryWrapper);
        //处理参数问题
        return changeParam(result);
    }

    // 按季度查询订单列表
    public AjaxResult listByQuarter(Page<GreenOrder> page, Integer year, Integer quarter, GreenOrderDTO dto) {
        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<GreenOrder> queryWrapper = buildDateRangeQuery(
                toUtilDate(startOfQuarter.atStartOfDay()),
                toUtilDate(endOfQuarter.atTime(23, 59, 59)), dto
        );

        Page<GreenOrder> result = greenOrderMapper.selectPage(page, queryWrapper);
        //处理参数问题
        return changeParam(result);
    }

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

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

        Page<GreenOrder> result = greenOrderMapper.selectPage(page, queryWrapper);
        //处理参数问题
        return changeParam(result);
    }


}
