package com.jwipc.finance.logic.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jwipc.dto.ExportDataDTO;
import com.jwipc.finance.convert.PaymentPlanSummaryConvert;
import com.jwipc.finance.dto.PaymentPlanSummaryDTO;
import com.jwipc.finance.entity.PaymentPlanSummary;
import com.jwipc.finance.logic.PaymentPlanSummaryLogic;
import com.jwipc.finance.model.po.*;
import com.jwipc.finance.model.query.PaymentPlanQuery;
import com.jwipc.finance.service.*;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.util.EasyExcelUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.time.temporal.WeekFields;
import java.util.*;

/**
 * @author 邓京术
 * @date 2025/07/22 11:39
 * @desc
 */
@Service
@RequiredArgsConstructor
public class PaymentPlanSummaryLogicImpl implements PaymentPlanSummaryLogic {
    private final PaymentPlanSummaryConvert paymentPlanSummaryConvert;
    private final IPaymentPlanSummaryService paymentPlanSummaryService;
    @Override
    public PageView findByPage(PaymentPlanQuery query) {
        final Page<PaymentPlanSummary> dbPage = PageUtil.toPage(query);
        List<PaymentPlanSummaryPO> paymentPlanSummaryPOList = paymentPlanSummaryService.findByPaymentPlanSummaryList(dbPage, query);
        List<PaymentPlanSummaryDTO> paymentPlanDTOS = paymentPlanSummaryConvert.po2PageListDTO(paymentPlanSummaryPOList);
        paymentPlanDTOS.stream().forEach(itemDTO->{
            if (null == query.getPaymentType() || "-1".equals(query.getPaymentType())) {
                if (null != itemDTO.getAppliedPaymentAmount() && itemDTO.getAppliedPaymentAmount().floatValue()!= 0f && null != itemDTO.getActualPayAmount() && itemDTO.getActualPayAmount().floatValue() != 0f) {
                    itemDTO.setDifferenceAmount(itemDTO.getAppliedPaymentAmount().subtract(itemDTO.getActualPayAmount()));
                    MathContext mc = new MathContext(4, RoundingMode.HALF_UP);
                    BigDecimal result = itemDTO.getDifferenceAmount().divide(itemDTO.getActualPayAmount(), mc);
                    itemDTO.setDifferencePercent(result);
                }
            }
        });
        return PageUtil.getPV(paymentPlanDTOS, dbPage.getTotal());
    }

    @Override
    public void exportPaymentPlanSumData(HttpServletResponse response, String exportFiled, PaymentPlanQuery paymentPlanQuery) {
        //需要查询一下总数
        paymentPlanQuery.setRows(10000);
        paymentPlanQuery.setPage(1);
        exportFiled = exportFiled.replace("differencePercent","differencePercentDesc");
        List<ExportDataDTO> exportDataDTOS = JSON.parseArray(exportFiled, ExportDataDTO.class);
        for (ExportDataDTO dataDTO : exportDataDTOS) {
            if ("currencyCode".equals(dataDTO.getField())){
//                dataDTO.setSelectList(currencies);
            }
        }
        final Page<PaymentPlanSummary> dbPage = PageUtil.toPage(paymentPlanQuery);
        dbPage.setMaxLimit(10000l);
        List<PaymentPlanSummaryPO> paymentPlanSummaryPOList = paymentPlanSummaryService.findByPaymentPlanSummaryList(dbPage, paymentPlanQuery);
        paymentPlanSummaryPOList.stream().forEach(itemDTO ->{
            WeekFields weekFields = WeekFields.of(Locale.getDefault());
            // 获取当前日期的周数（周一作为一周的开始）
//            int weekOfMonth = itemDTO.getPaymentExpireDate().get(weekFields.weekOfMonth());
//            itemDTO.setPaymentPlanWeek(weekOfMonth + "");
            if (null == paymentPlanQuery.getPaymentType() || "-1".equals(paymentPlanQuery.getPaymentType())) {
                if (null != itemDTO.getAppliedPaymentAmount() && itemDTO.getAppliedPaymentAmount().floatValue()!= 0f && null != itemDTO.getActualPayAmount() && itemDTO.getActualPayAmount().floatValue() != 0f) {
                    itemDTO.setDifferenceAmount(itemDTO.getAppliedPaymentAmount().subtract(itemDTO.getActualPayAmount()));
                    MathContext mc = new MathContext(4, RoundingMode.HALF_UP);
                    BigDecimal result = itemDTO.getDifferenceAmount().divide(itemDTO.getActualPayAmount(), mc);
                    itemDTO.setDifferencePercent(result);
                    itemDTO.setDifferencePercentDesc(itemDTO.getDifferencePercent().multiply(new BigDecimal(100)) + "%");
                }
            } else {
                if (itemDTO.getPaymentType().equals("D")) {
                    itemDTO.setPaymentType("对账款");
                } else {
                    itemDTO.setPaymentType("预付款");
                }

                //设置差异百分比
                if (itemDTO.getDifferencePercent() != null) {
                    itemDTO.setDifferencePercentDesc(itemDTO.getDifferencePercent().multiply(new BigDecimal(100)) + "%");
                }
            }

        });
        //同步执行
        try {
            EasyExcelUtils.trendsModelWriteTow(response,
                    "付款计划汇总数据-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN), "sheet", paymentPlanSummaryPOList,
                    exportDataDTOS);
        } catch (IOException e) {
            throw new RuntimeException("导出excel文档失败.");
        }
    }
}
