package com.ruoyi.novel.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.novel.domain.RoyaltyReport;
import com.ruoyi.novel.domain.RoyaltySummary;
import com.ruoyi.novel.mapper.RoyaltySummaryMapper;
import com.ruoyi.novel.service.IFinanceService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

// FinanceServiceImpl.java
@Service
public class FinanceServiceImpl implements IFinanceService {
    private static final Logger logger = LoggerFactory.getLogger(FinanceServiceImpl.class);
    @Autowired
    private RoyaltySummaryMapper royaltySummaryMapper;
    @Value("${royalty.base.rate:0.15}")
    private BigDecimal baseRoyaltyRate;

    @Value("${handling.fee.rate:0.05}")
    private BigDecimal handlingFeeRate;
    @Value("${royalty.rate}")
    private BigDecimal royaltyRate;

    //@Value("${handling.fee.rate}")
    //private BigDecimal handlingFeeRate;

    @Override
    public RoyaltyReport calculateRoyalty(Long authorId, String month) {
        // 1. 从PHP系统拉取数据（补充缺失的调用）
//        RoyaltySummary summary = phpApiClient.getAuthorRoyaltySummary(authorId, month);
//        // 2. 计算分成金额（补充业务逻辑）
//        BigDecimal royaltyRate = getRoyaltyRate(authorId);
//        BigDecimal grossAmount = summary.getTotalReads().multiply(royaltyRate);
//        BigDecimal handlingFee = grossAmount.multiply(handlingFeeRate);
//        BigDecimal netAmount = grossAmount.subtract(handlingFee);
//        // 3. 构建报表对象
//        return new RoyaltyReport(authorId, month, summary.getTotalReads(),
//                royaltyRate, handlingFeeRate, handlingFee, netAmount);
        // 1. 从PHP主库获取基础数据（假设已通过定时任务同步）
        RoyaltySummary summary = royaltySummaryMapper.selectByAuthorAndMonth(authorId, month);

//        if (summary == null) {
//            throw new ServiceException("No data found for author: " + authorId + " in " + month);
//        }
        if (summary == null) {
            throw new ServiceException("未找到分账数据: author=" + authorId + ", month=" + month);
        }
        // 2. 计算实际分成比例（可根据作者等级调整）
        BigDecimal actualRate = getRoyaltyRate(authorId);
        // 3. 构建报表
        RoyaltyReport report = new RoyaltyReport();
        report.setAuthorId(authorId);
        report.setMonth(month);
        report.calculate(summary.getTotalReads(), actualRate, handlingFeeRate);

        return report;

        // 2. 计算分账金额
//        BigDecimal rawAmount = summary.getTotalReads().multiply(royaltyRate);
//        BigDecimal handlingFee = rawAmount.multiply(handlingFeeRate);
//        BigDecimal netAmount = rawAmount.subtract(handlingFee);
//
//        // 3. 构建报表
//        return new RoyaltyReport(
//                authorId,
//                month,
//                summary.getTotalReads(),
//                royaltyRate,
//                handlingFeeRate,
//                handlingFee,
//                netAmount
//        );
    }

    @Override
    @Scheduled(cron = "0 0 2 * * ?") // 每天凌晨2点执行
    public void syncRoyaltyData() {
        logger.info("开始同步分账数据...");
        try {
            // 1. 从PHP主库获取数据
            List<RoyaltySummary> summaries = fetchFromPhpSystem();

            // 2. 更新到本地数据库
            summaries.forEach(summary -> {
                royaltySummaryMapper.upsertSummary(summary);
            });

            logger.info("同步完成: {}条记录", summaries.size());
        } catch (Exception e) {
            logger.error("分账数据同步失败: {}", e.getMessage());
        }
    }

    private List<RoyaltySummary> fetchFromPhpSystem() {
        // 实现从PHP系统获取数据的逻辑
        // 返回模拟数据
        List<RoyaltySummary> list = new ArrayList<>();
        list.add(new RoyaltySummary(1001L, "2023-10", new BigDecimal("15000.00")));
        list.add(new RoyaltySummary(1002L, "2023-10", new BigDecimal("8500.00")));
        return list;
    }

    @Override
    public BigDecimal getRoyaltyRate(Long authorId) {
        // 实际应根据作者等级计算
        // 这里返回基础比例
        return baseRoyaltyRate;
    }

    @Override
    public BigDecimal getHandlingFeeRate() {
        return handlingFeeRate;
    }


//    @Override
//    public RoyaltyReport calculateRoyalty(Long authorId, String month) {
//        // 1. 从PHP系统拉取数据（补充缺失的调用）
//        RoyaltySummary summary = phpApiClient.getAuthorRoyaltySummary(authorId, month);
//
//        // 2. 计算分成金额（补充业务逻辑）
//        BigDecimal royaltyRate = getRoyaltyRate(authorId);
//        BigDecimal grossAmount = summary.getTotalReads().multiply(royaltyRate);
//        BigDecimal handlingFee = grossAmount.multiply(handlingFeeRate);
//        BigDecimal netAmount = grossAmount.subtract(handlingFee);
//
//        // 3. 构建报表对象
//        return new RoyaltyReport(authorId, month, summary.getTotalReads(),
//                royaltyRate, handlingFeeRate, handlingFee, netAmount);
//    }
//
//    // 补充缺失的辅助方法
//    private BigDecimal getRoyaltyRate(Long authorId) {
//        Author author = authorService.getById(authorId);
//        BigDecimal rate = baseRoyaltyRate;
//        if (author.isVip()) {
//            rate = rate.add(vipBonusRate); // VIP作者加成
//        }
//        return rate.min(new BigDecimal("0.35")); // 上限35%:cite[4]
//    }
}
