package com.jwipc.finance.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.google.common.collect.Lists;
import com.jwipc.finance.entity.PaymentPlan;
import com.jwipc.finance.entity.PaymentPlanDetail;
import com.jwipc.finance.mapper.PaymentPlanMapper;
import com.jwipc.finance.model.po.AccountStatementPO;
import com.jwipc.finance.model.po.CreatePcaDetailPO;
import com.jwipc.finance.model.po.PaymentPlanPO;
import com.jwipc.finance.model.query.AccountStatementQuery;
import com.jwipc.finance.model.query.PaymentPlanQuery;
import com.jwipc.finance.service.IAccountStatementService;
import com.jwipc.finance.service.IInvoicedApplyDetailService;
import com.jwipc.finance.service.IPaymentPlanDetailService;
import com.jwipc.finance.service.IPaymentPlanService;
//import com.jwipc.security.LoginUtil;
//import com.jwipc.sys.client.SequenceClient;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import static com.jwipc.constant.SequenceConfigConst.REDIS_KEY_PREFIX;

/**
 * <p>
 * 对账模块-付款计划主表 服务实现类
 * </p>
 *
 * @author 邓京术
 * @since 2025-07-14
 */
@Service
@RequiredArgsConstructor
public class PaymentPlanServiceImpl extends ServiceImpl<PaymentPlanMapper, PaymentPlan> implements IPaymentPlanService {

    private final IAccountStatementService accountStatementService;
    private final IInvoicedApplyDetailService invoicedApplyDetailService;
    private final IPaymentPlanDetailService paymentPlanDetailService;
//    private final SequenceClient sequenceClient;

    @Override
    public List<PaymentPlanPO> findPageByQuery(Page<PaymentPlan> dbPage, PaymentPlanQuery query) {
        if (dbPage==null){
            return baseMapper.findPageByQuery(query);
        }
        return baseMapper.findPageByQuery(dbPage,query);
    }

    @Override
    public PaymentPlanPO selectPoById(Long id) {
        return baseMapper.selectPoById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void addNewPaymentPlan(String paymentPlanYear,String paymentPlanMonth) throws Exception {
        //检查数据库是否已经存在当月付款计划单
//        AccountStatementQuery query = new AccountStatementQuery();
//        query.setAccountStatementYear(paymentPlanYear + "" + paymentPlanMonth);
//        List<AccountStatementPO> accountOrApplyList = accountStatementService.findAccountStatementByYM(query);
//        final String no = "YSD" + paymentPlanYear + paymentPlanMonth + "01";
//
//        // 对账单主表
//        PaymentPlan paymentPlan = new PaymentPlan();
//        paymentPlan.setPaymentPlanNo(no);
//        paymentPlan.setStatus(1);
//        paymentPlan.setPaymentPlanYear(paymentPlanYear);
//        paymentPlan.setPaymentPlanMonth(paymentPlanMonth);
//        paymentPlan.setCreateTime(LocalDateTime.now());
//        paymentPlan.setCreateUserId(LoginUtil.getUserId());
//        paymentPlan.setCreateUserCode(LoginUtil.getAccount());
//        paymentPlan.setCreateUserName(LoginUtil.getName());
//        paymentPlan.setDeleteFlag(0);
//        saveOrUpdate(paymentPlan);
//
//        List<PaymentPlanDetail> paymentPlanDetails = Lists.newArrayList();
//        for(AccountStatementPO accountStatementPO: accountOrApplyList) {
//            //发票资料交接页面，实际未付金额fin_invoiced_apply ActualUnpaidAmount
//            BigDecimal actualUnpaidAmount = accountStatementPO.getActualUnpaidAmount();
//
//            //对账单付款申请请款
//            List<CreatePcaDetailPO>  createPcaDetailPOS = invoicedApplyDetailService.queryCodApplyInvoiceListByAccountStatementNo(accountStatementPO.getAccountStatementNo());
//            //预付款申请请款
//
//
//            //计算付款申请明细中的本次申请金额总和
//            BigDecimal budOutMoneySum = BigDecimal.ZERO;
//            BigDecimal appliedUnpaidAmountHis = BigDecimal.ZERO;
//
//            BigDecimal finishMoneySum = BigDecimal.ZERO;//已经付款完成的合计
//            //统计未付金额及应付金额
//            for (CreatePcaDetailPO createPcaDetailPO : createPcaDetailPOS) {
//                budOutMoneySum = budOutMoneySum.add(createPcaDetailPO.getBudOutMoney());
//
//                //排除已经付款完成的  fin_payment_cod_apply 付款申请主表 status == 5}
//                if (createPcaDetailPO.getStatus() != null && createPcaDetailPO.getStatus() == 5) {
//                    //付款完成的累加
//                    finishMoneySum = finishMoneySum.add(createPcaDetailPO.getBudOutMoney());
//                } else {
//                    //计算未付款历史的总和（状态不是付款完成的） 申请金额累加
//                    appliedUnpaidAmountHis = appliedUnpaidAmountHis.add(createPcaDetailPO.getBudOutMoney());
//                }
//            }
//            //开票申请中的“实际未付金额fin_invoiced_apply actual_unpaid_amount - 所有此对账单的付款申请中的本次申请金额累加， 申请明细字段fin_payment_cod_apply_detail bud_out_money
//            BigDecimal totalUnpaidAmount = actualUnpaidAmount.subtract(budOutMoneySum);
//            if (totalUnpaidAmount.floatValue() <= 0) continue;
//
//            PaymentPlanDetail paymentPlanDetail = new PaymentPlanDetail();//paymentPlanDetailConvert.po2Entity(accountStatementPO);
//            paymentPlanDetail.setAppliedUnpaidAmount(appliedUnpaidAmountHis);
//            //设置应付金额 = 发票实际未付金额(actualUnpaidAmount) - 申请单已经付款完成的金额(finishMoneySum)
//            paymentPlanDetail.setActualPayAmount(actualUnpaidAmount.subtract(finishMoneySum));
//            //根据付款计划单月份 顺序流水
//            final String itemNo = "";//sequenceClient.getCodeSequenceNo(paymentPlan.getPaymentPlanNo() , "payment_plan_code",1);
//            paymentPlanDetail.setPaymentPlanDetailNo(Integer.parseInt(itemNo));
//            paymentPlanDetail.setCreateUserId(LoginUtil.getUserId());
//            paymentPlanDetail.setCreateUserCode(LoginUtil.getAccount());
//            paymentPlanDetail.setCreateUserName(LoginUtil.getName());
//            paymentPlanDetail.setCreateTime(LocalDateTime.now());
//            paymentPlanDetail.setPaymentPlanId(paymentPlan.getId());
//            paymentPlanDetail.setPaymentPlanNo(paymentPlan.getPaymentPlanNo());
//            paymentPlanDetail.setStatus(1);
//            paymentPlanDetail.setAccountStatementNo(accountStatementPO.getAccountStatementNo());
//            paymentPlanDetail.setAccountStatementYear(accountStatementPO.getAccountStatementYear());
//            paymentPlanDetail.setAccountStatementMonth(accountStatementPO.getAccountStatementMonth());
//            paymentPlanDetail.setCompanyCode(accountStatementPO.getCompanyCode());
//            paymentPlanDetail.setSupplierCode(accountStatementPO.getSupplierCode());
//            paymentPlanDetail.setSupplierName(accountStatementPO.getSupplierName());
//            paymentPlanDetail.setCurrencyCode(accountStatementPO.getCurrencyCode());
//            paymentPlanDetail.setPurchaseGroup(accountStatementPO.getPurchaseGroup());
//            paymentPlanDetail.setPaymentWay(accountStatementPO.getPaymentWay());
//            paymentPlanDetail.setPaymentExpireDate(accountStatementPO.getPaymentExpireDate());
//            paymentPlanDetail.setPaymentTermCode(accountStatementPO.getPaymentTermCode());
//            paymentPlanDetail.setDeleteFlag(0);
//            paymentPlanDetails.add(paymentPlanDetail);
//        }
//        if(!paymentPlanDetailService.saveBatch(paymentPlanDetails)){
//            throw new Exception("保存付款单明细数据失败, 请联系管理员");
//        }
    }
}
