package com.kym.admin.jobs;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.kym.entity.miniapp.ChargeOrder;
import com.kym.entity.miniapp.Invoice;
import com.kym.entity.wechat.InvoiceOrderDetail;
import com.kym.huapiaoer.enums.InvoiceQueryType;
import com.kym.service.miniapp.ChargeOrderService;
import com.kym.service.miniapp.HuapiaoerInvoiceService;
import com.kym.service.miniapp.InvoiceService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class InvoiceStatusJob {

    private final InvoiceService invoiceService;
    private final ChargeOrderService chargeOrderService;
    private final HuapiaoerInvoiceService huapiaoerInvoiceService;

    public InvoiceStatusJob(InvoiceService invoiceService, ChargeOrderService chargeOrderService,
                            HuapiaoerInvoiceService huapiaoerInvoiceService) {
        this.invoiceService = invoiceService;
        this.chargeOrderService = chargeOrderService;
        this.huapiaoerInvoiceService = huapiaoerInvoiceService;
    }

    /**
     * 每5分钟轮询航信查询开票结果，处理开票中的发票，并对已开票但未插卡包的发票补插
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void execute() {
        log.info("执行发票状态轮询任务...开始");

        // 第一阶段：处理开票中的发票
        List<Invoice> invoiceList;
        try {
            DynamicDataSourceContextHolder.push("db-miniapp");
            invoiceList = invoiceService.lambdaQuery().eq(Invoice::getStatus, Invoice.STATUS_开票中).list();
        } finally {
            DynamicDataSourceContextHolder.poll();
        }

        for (Invoice invoice : invoiceList) {
            try {
                var result = huapiaoerInvoiceService.queryInvoiceResult(invoice.getApplyId(), InvoiceQueryType.BLUE.getCode());

                huapiaoerInvoiceService.updateInvoiceDetailFromResult(invoice, result);

                var startChargeSeqs = invoice.getOrderDetails().stream().map(InvoiceOrderDetail::getStartChargeSeq).toList();
                try {
                    DynamicDataSourceContextHolder.push("db-miniapp");
                    chargeOrderService.lambdaUpdate().set(ChargeOrder::getInvoiceStatus, ChargeOrder.INVOICE_STATUS_已开票)
                            .in(ChargeOrder::getStartChargeSeq, startChargeSeqs).update();
                    invoiceService.lambdaUpdate().set(Invoice::getStatus, Invoice.STATUS_已开票)
                            .eq(Invoice::getApplyId, invoice.getApplyId()).update();
                } finally {
                    DynamicDataSourceContextHolder.poll();
                }

                // 邮件已由航信在开票时根据 head.recmail 自动发送，无需重复调用

                log.info("发票轮询处理成功, applyId:{}, invoiceCode:{}, invoiceNumber:{}",
                        invoice.getApplyId(), result.getInvoicecode(), result.getInvoicenumber());
            } catch (Exception e) {
                log.error("发票轮询处理失败, applyId:{}", invoice.getApplyId(), e);
            }
        }

        log.info("执行发票状态轮询任务...结束");
    }

}
