package com.zksy.property.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.property.domain.ARefund;
import com.zksy.property.domain.vo.ARefundVo;
import com.zksy.property.mapper.ARefundMapper;
import com.zksy.property.service.ARefundService;
import com.zksy.service.MinioFileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【a_refund(退款信息表)】的数据库操作Service实现
* @createDate 2025-07-29 15:30:56
*/
@Service
public class ARefundServiceImpl extends ServiceImpl<ARefundMapper, ARefund>
    implements ARefundService{

    @Autowired
    private ARefundMapper aRefundMapper;

    @Override
    public Page<ARefund> findByPage(long pageNum, long pageSize, String unit, String tenant, String generationDate) {
        Page<ARefund> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<ARefund> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(unit != null,ARefund::getUnit,unit);
        queryWrapper.like(tenant != null,ARefund::getTenant,tenant);
        queryWrapper.like(generationDate != null,ARefund::getGenerationDate,generationDate);
        Page<ARefund> page1 = this.page(page, queryWrapper);
        return page1;
    }

    @Override
    public List<ARefund> getARefundList(String unit, String tenant, String generationDate) {
        LambdaQueryWrapper<ARefund> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(unit != null,ARefund::getUnit,unit);
        queryWrapper.like(tenant != null,ARefund::getTenant,tenant);
        queryWrapper.like(generationDate != null,ARefund::getGenerationDate,generationDate);
        List<ARefund> list = this.list(queryWrapper);
        return list;
    }

    @Override
    public Map<String, BigDecimal> calculateMonthlyRefundStatistics(int year) {
        // 从数据库查询指定年份的所有退款记录
        List<ARefund> refundList = list(new QueryWrapper<ARefund>()
                .ge("generation_date", LocalDate.of(year, 1, 1))
                .le("generation_date", LocalDate.of(year, 12, 31)));

        Map<String, BigDecimal> monthlyData = new LinkedHashMap<>();
        for (int month = 1; month <= 12; month++) {
            monthlyData.put(String.format("%d-%02d", year, month), BigDecimal.ZERO);
        }

        for (ARefund refund : refundList) {
            if (refund.getGenerationDate() != null && refund.getTotalAmount() != null) {
                String monthKey = String.format("%d-%02d",
                        year,
                        refund.getGenerationDate().getMonthValue()
                );
                monthlyData.merge(monthKey, refund.getTotalAmount(), BigDecimal::add);
            }
        }

        return monthlyData;
    }


    @Override
    public Map<String, BigDecimal> calculateQuarterlyRefundStatistics(int year) {
        List<ARefund> refundList = list(new QueryWrapper<ARefund>()
                .ge("generation_date", LocalDate.of(year, 1, 1))
                .le("generation_date", LocalDate.of(year, 12, 31)));

        // 初始化4个季度的容器（使用LinkedHashMap保证顺序）
        Map<String, BigDecimal> quarterlyData = new LinkedHashMap<>();
        for (int quarter = 1; quarter <= 4; quarter++) {
            quarterlyData.put(year + "Q" + quarter, BigDecimal.ZERO);
        }

        for (ARefund refund : refundList) {
            LocalDate date = refund.getGenerationDate();
            if (date != null && refund.getTotalAmount() != null) {
                int quarter = (date.getMonthValue() - 1) / 3 + 1;
                String quarterKey = year + "Q" + quarter;
                quarterlyData.merge(quarterKey, refund.getTotalAmount(), BigDecimal::add);
            }
        }

        return quarterlyData;
    }

    @Override
    public Map<String, BigDecimal> calculateYearlyRefundStatistics() {
        List<ARefund> refundList = list();
        Map<String, BigDecimal> yearlyData = new TreeMap<>();

        // 统计数据
        for (ARefund refund : refundList) {
            LocalDate date = refund.getGenerationDate();
            if (date != null && refund.getTotalAmount() != null) {
                String yearKey = String.valueOf(date.getYear());
                yearlyData.merge(yearKey, refund.getTotalAmount(), BigDecimal::add);
            }
        }

        return yearlyData;
    }

    @Override
    public List<Integer> getExistingRefundYears() {
        List<ARefund> refundList = list();
        return refundList.stream()
                .map(ARefund::getGenerationDate)
                .filter(Objects::nonNull)
                .map(date -> date.getYear())
                .distinct()
                .sorted()
                .collect(Collectors.toList());
    }

    @Autowired
    private MinioFileStorageService minioFileStorageService;

    @Override
    @Transactional
    public boolean removeBatchByIdsWithUrl(List<String> ids) {
        List<ARefund> aReceiptInfoList = listByIds(ids);
        List<String> list = aReceiptInfoList.stream().map(ARefund::getAttachmentUrl).collect(Collectors.toList());
        minioFileStorageService.deleteFileBatch(list);
        return removeBatchByIds(ids);
    }

    @Override
    public Page<ARefundVo> findByPageWithContract(long pageNum, long pageSize, String unit, String tenant, String contractNumber) {
        Page<ARefundVo> page = new Page<>(pageNum, pageSize);
        return aRefundMapper.selectRefundWithContractByPage(page, unit, tenant, contractNumber);
    }
}




