package com.trade.admin.job;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSONArray;
import com.trade.common.utils.ConstantUtil;
import com.trade.common.utils.DateUtils;
import com.trade.common.utils.LoggerUtil;
import com.trade.common.utils.StringUtils;
import com.trade.common.utils.bean.Builder;
import com.trade.service.filestorage.enums.FileTypeEnum;
import com.trade.service.filestorage.entity.BusinessRelateFile;
import com.trade.service.filestorage.entity.TFileStorage;
import com.trade.service.filestorage.enums.FileModuleEnum;
import com.trade.service.filestorage.service.BusinessRelateFileBaseService;
import com.trade.service.filestorage.service.OSSFileService;
import com.trade.service.thirdparty.xiaotu.dto.*;
import com.trade.service.thirdparty.xiaotu.service.XiaotuRequestService;
import com.trade.service.thirdparty.xiaotu.utils.MultipartFileExtend;
import com.trade.service.thirdparty.xiaotu.utils.XiaoTuUtil;
import com.trade.service.trade.purchaseorder.domain.PurchaseOrderInvoice;
import com.trade.service.trade.purchaseorder.service.PurchaseOrderInvoiceService;
import com.trade.service.trade.purchaseorder.service.PurchaseOrderService;
import com.trade.service.trade.purchaseorder.vo.TradingPlatformInvoiceVo;
import org.slf4j.Logger;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: 采购发票定时任务
 * @Author: wanglang
 * @Date: 2024/9/23
 * @Version: 1.0
 */
@Component
public class PurchaseInvoiceSchedule {

    private static final Logger log = LoggerUtil.logger(LoggerUtil.LogFileNameEnum.SERVICES_LOG);
    @Resource
    private PurchaseOrderService purchaseOrderService;
    @Resource
    private XiaotuRequestService xiaotuRequestService;
    @Resource
    private PurchaseOrderInvoiceService purchaseOrderInvoiceService;
    @Resource
    private OSSFileService ossFileService;
    @Resource
    private BusinessRelateFileBaseService businessRelateFileBaseService;

    /**
     * 定时去小图拉取采购发票数据
     */
    @Scheduled(cron = "0 17 1 * * ?")
    public void purchaseInvoiceTsk() {
        log.info("代理模式采购发票定时任务开始");
        pullPurchaseInvoice(null, 1);
        log.info("代理模式采购发票定时任务结束");
    }

    /**
     * 定时去小图拉取采购发票数据
     */
    @Scheduled(cron = "0 27 1 * * ?")
    public void purchaseClienInvoiceTsk() {
        log.info("非代理模式采购发票定时任务开始");
        pullPurchaseInvoice(null, 2);
        log.info("非代理模式采购发票定时任务结束");
    }

    /**
     * 定时去小图下载采购发票数据
     */
    @Scheduled(cron = "0 10 4 * * ?")
    public void pullInvoiceFileTask() {
        pullInvoiceDetail(null);
    }

    /**
     * 定时处理采购发票认证状态
     */
    @Scheduled(cron = "0 39 2 * * ?")
    public void handleInvoiceCertificationStatus() {
        List<PurchaseOrderInvoice> orderInvoiceList = purchaseOrderInvoiceService.selectByInvoiceStatus("N");
        for (PurchaseOrderInvoice purchaseOrderInvoice : orderInvoiceList) {
            InvoiceQueryRequset invoiceQueryRequset = new InvoiceQueryRequset();
            if (StringUtils.isNotEmpty(purchaseOrderInvoice.getInvoiceNumber())) {
                JSONArray pfphms = new JSONArray();
                pfphms.add(purchaseOrderInvoice.getInvoiceNumber());
                invoiceQueryRequset.setFphms(pfphms);
            }
            if (StringUtils.isNotEmpty(purchaseOrderInvoice.getDigitalInvoiceNumber())) {
                JSONArray sdfphms = new JSONArray();
                sdfphms.add(purchaseOrderInvoice.getDigitalInvoiceNumber());
                invoiceQueryRequset.setSdfphms(sdfphms);
            }
            invoiceQueryRequset.setPage(1);
            invoiceQueryRequset.setPageSize(10);
            List<Long> orderIds = new ArrayList<>();
            orderIds.add(purchaseOrderInvoice.getOrderId());
            List<TradingPlatformInvoiceVo> invoiceVos;
            if (purchaseOrderInvoice.getSource() == 1) {
                invoiceVos = purchaseOrderService.queryCustTaxNum(orderIds, null);
            } else {
                invoiceVos = purchaseOrderService.queryClientTaxNum(orderIds, null);
            }
            TradingPlatformInvoiceVo invoiceVo = invoiceVos.get(0);
            BusinessCommonRequest businessCommonRequest = new BusinessCommonRequest();
            businessCommonRequest.setXtEid(invoiceVo.getXtEid());
            businessCommonRequest.setXtUid(invoiceVo.getXtUserId());
            businessCommonRequest.setCustomerId(invoiceVo.getCustomerUserId());
            List<InvoiceQueryResponse> invoiceQueryResponses = xiaotuRequestService.invoiceQuery(invoiceQueryRequset,
                    businessCommonRequest);
            if (CollectionUtil.isNotEmpty(invoiceQueryResponses)) {
                InvoiceQueryResponse invoiceQueryResponse = invoiceQueryResponses.get(0);
                if ("Y".equals(invoiceQueryResponse.getRzxfzzszyfpbz())) {
                    purchaseOrderInvoice.setInvoiceStatus(invoiceQueryResponse.getRzxfzzszyfpbz());
                    if (invoiceQueryResponse.getRzrq() != null) {
                        purchaseOrderInvoice
                                .setCertificationDate(DateUtils.longToLocalDate(invoiceQueryResponse.getRzrq()));
                    }
                    purchaseOrderInvoiceService.updateById(purchaseOrderInvoice);
                }
            }
        }
    }

    /**
     * 根据订单号拉取采购发票数据
     * 
     * @param orderIds
     */
    public void pullPurchaseInvoice(List<Long> orderIds, int source) {
        List<TradingPlatformInvoiceVo> invoiceVos;
        if (source == 1) {
            invoiceVos = purchaseOrderService.queryCustTaxNum(orderIds, null);
        } else {
            invoiceVos = purchaseOrderService.queryClientTaxNum(orderIds, null);
        }
        for (TradingPlatformInvoiceVo invoiceVo : invoiceVos) {
            try {
                BusinessCommonRequest businessCommonRequest = new BusinessCommonRequest();
                businessCommonRequest.setXtEid(invoiceVo.getXtEid());
                businessCommonRequest.setXtUid(invoiceVo.getXtUserId());
                businessCommonRequest.setCustomerId(invoiceVo.getCustomerUserId());
                InvoiceQueryRequset invoiceQueryRequset = new InvoiceQueryRequset();
                invoiceQueryRequset.setXhfnsrsbh(invoiceVo.getTaxNum());
                invoiceQueryRequset.setPage(1);
                invoiceQueryRequset.setPageSize(30);
                List<PurchaseOrderInvoice> purchaseOrderInvoices = purchaseOrderInvoiceService
                        .getByOrderId(invoiceVo.getOrderId());
                int isPull = 1;
                if (CollectionUtil.isNotEmpty(purchaseOrderInvoices)) {
                    isPull = isPull + 1;
                }
                for (int j = 0; j < isPull; j++) {
                    if (isPull == 2) {
                        if (j == 0) {
                            invoiceQueryRequset
                                    .setLrrqQ(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                            invoiceQueryRequset
                                    .setLrrqZ(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                        }
                        if (j == 1) {
                            invoiceQueryRequset.setLrrqQ(null);
                            invoiceQueryRequset.setLrrqZ(null);
                            invoiceQueryRequset
                                    .setXgrqQ(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                            invoiceQueryRequset
                                    .setXgrqZ(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                        }
                    }
                    List<InvoiceQueryResponse> invoiceQueryResponses = xiaotuRequestService
                            .invoiceQuery(invoiceQueryRequset, businessCommonRequest);
                    List<InvoiceQueryResponse> invoiceQueryResponseList = new ArrayList<>();
                    while (CollectionUtil.isNotEmpty(invoiceQueryResponses)) {
                        invoiceQueryRequset.setPage(invoiceQueryRequset.getPage() + 1);
                        invoiceQueryResponses = invoiceQueryResponses.stream().filter(
                                i -> StringUtils.isNotEmpty(i.getBz()) && i.getBz().contains(invoiceVo.getOrderNo()))
                                .collect(Collectors.toList());
                        invoiceQueryResponseList.addAll(invoiceQueryResponses);
                        invoiceQueryResponses = xiaotuRequestService.invoiceQuery(invoiceQueryRequset,
                                businessCommonRequest);
                    }
                    if (CollectionUtil.isNotEmpty(invoiceQueryResponseList)) {
                        invoiceQueryResponseList = invoiceQueryResponseList.stream()
                                .filter(i -> "N".equals(i.getZfbz1()) && "N".equals(i.getHcbz1()))
                                .collect(Collectors.toList());
                        purchaseOrderService.handleOrderInvoice(invoiceQueryResponseList, invoiceVo.getOrderId(),
                                invoiceVo.getAmountTotal(), source);
                    }
                }
            } catch (Exception e) {
                log.error("拉取发票失败orderId={},customerUserId={},e={}", invoiceVo.getOrderId(),
                        invoiceVo.getCustomerUserId(), e);
            }
        }
    }

    public void pullInvoiceDetail(List<Long> invoiceIds) {
        List<PurchaseOrderInvoice> invoices = purchaseOrderInvoiceService.getByInvoiceStatus("Y", invoiceIds);
        for (PurchaseOrderInvoice invoice : invoices) {
            try {
                handleInvoiceFile(invoice);
            } catch (Exception e) {
                log.error("下载发票失败orderId={},invoice={},e={}", invoice.getOrderId(), invoice.getId(), e);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void handleInvoiceFile(PurchaseOrderInvoice invoice) throws Exception {
        List<Long> orderId = new ArrayList<>();
        orderId.add(invoice.getOrderId());
        TradingPlatformInvoiceVo invoiceVo;
        if (invoice.getSource() == 1) {
            invoiceVo = purchaseOrderService.queryCustTaxNum(orderId, null).stream().findAny().get();
        } else {
            invoiceVo = purchaseOrderService.queryClientTaxNum(orderId, null).stream().findAny().get();
        }
        BusinessCommonRequest businessCommonRequest = new BusinessCommonRequest();
        businessCommonRequest.setXtEid(invoiceVo.getXtEid());
        businessCommonRequest.setXtUid(invoiceVo.getXtUserId());
        businessCommonRequest.setCustomerId(invoiceVo.getCustomerUserId());
        InvoiceFileResponse invoiceFileResponse = xiaotuRequestService.invoiceFileQuery(invoice.getPurchaseVoucherNo(),
                businessCommonRequest);
        TFileStorage fileStorage = ossFileService.addStorageWithBase64Str(invoiceFileResponse.getFileName(),
                invoiceFileResponse.getBlob(), FileModuleEnum.PURCHASE_ORDER);
        BusinessRelateFile businessRelateFile = Builder.of(BusinessRelateFile.class)
                .with(BusinessRelateFile::setBelongId, invoice.getId())
                .with(BusinessRelateFile::setBelongType, ConstantUtil.PURCHASE_ORDER)
                .with(BusinessRelateFile::setFileType, FileTypeEnum.PURCHASE_ORDER_INVOICE.getCode())
                .with(BusinessRelateFile::setFileId, fileStorage.getId()).build();
        businessRelateFileBaseService.upsertBusinessRelateFiles(businessRelateFile);
        invoice.setPullState(1);
        purchaseOrderInvoiceService.updateById(invoice);
    }
}
