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.InvoiceNotification;
import com.kym.entity.wechat.InvoiceOrderDetail;
import com.kym.service.admin.InvoiceDetailService;
import com.kym.service.miniapp.ChargeOrderService;
import com.kym.service.miniapp.InvoiceService;
import com.kym.service.wechat.WxPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author skyline
 * @description 发票状态更新
 */
@Component
@Slf4j
public class InvoiceStatusJob {

    private final InvoiceService invoiceService;

    private final InvoiceDetailService invoiceDetailService;

    private final ChargeOrderService chargeOrderService;

    private final WxPayService wxPayService;


    public InvoiceStatusJob(InvoiceService invoiceService, InvoiceDetailService invoiceDetailService, ChargeOrderService chargeOrderService, WxPayService wxPayService) {
        this.invoiceService = invoiceService;
        this.invoiceDetailService = invoiceDetailService;
        this.chargeOrderService = chargeOrderService;
        this.wxPayService = wxPayService;
    }

    /**
     * 每天18:00执行，处理微信发票开票结果通知不到的情况，主动查询发票信息更新数据
     */
    @Scheduled(cron = "0 0 18 * * ?")
    public void execute() {
        log.info("执行发票状态处理定时任务...开始");
        // 所有开票中状态的发票
        DynamicDataSourceContextHolder.push("db-miniapp");
        var invoiceList = invoiceService.lambdaQuery().eq(Invoice::getStatus, Invoice.STATUS_开票中).list();
        DynamicDataSourceContextHolder.poll();
        invoiceList.forEach(invoice -> {
            var fapiaoApplications = wxPayService.queryFapiao(invoice.getApplyId());
            // 更新发票详情
            invoiceDetailService.updateInvoiceDetail(invoice.getApplyId(), fapiaoApplications);
            // 更新订单开票状态
            if (InvoiceNotification.FapiaoStatus.ISSUED.name().equals(fapiaoApplications.getFapiao_information().get(0).getStatus())) {
                var startChargeSeqs = invoice.getOrderDetails().stream().map(InvoiceOrderDetail::getStartChargeSeq).toList();
                DynamicDataSourceContextHolder.push("db-miniapp");
                chargeOrderService.lambdaUpdate().in(ChargeOrder::getStartChargeSeq, startChargeSeqs).set(ChargeOrder::getInvoiceStatus, ChargeOrder.INVOICE_STATUS_已开票).update();
                // 修改发票状态
                invoiceService.lambdaUpdate().eq(Invoice::getApplyId, invoice.getApplyId()).set(Invoice::getStatus, Invoice.STATUS_已开票).update();
                DynamicDataSourceContextHolder.poll();
            }
        });
        log.info("执行发票状态处理定时任务...结束");
    }

}
