package com.fs.his.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fs.common.utils.PubFun;
import com.fs.his.domain.FsStoreOrder;
import com.fs.his.domain.FsStoreOrderBillLog;
import com.fs.his.service.IFsStoreOrderBillLogService;
import com.fs.his.service.IFsStoreOrderService;
import com.fs.nuonuo.NuonuoUtils;
import com.fs.nuonuo.vo.InvoiceRedVo;
import com.fs.nuonuo.vo.InvoiceResultVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Component("billTask")
@AllArgsConstructor
public class BillTask {

    private final IFsStoreOrderBillLogService fsStoreOrderBillLogService;
    private final IFsStoreOrderService fsStoreOrderService;

    /**
     * 查询发票信息，同步数据
     */
    @Transactional
    public void bill(){
        log.debug("发票信息同步");
        List<FsStoreOrderBillLog> list = fsStoreOrderBillLogService.list(new QueryWrapper<FsStoreOrderBillLog>().in("status", 20).eq("upload_api", 1));
        if(list.isEmpty()) return;
        PubFun.batchProcessing(50, list, this::updateData);

        log.debug("冲红信息同步");
        List<FsStoreOrderBillLog> list2 = fsStoreOrderBillLogService.list(new QueryWrapper<FsStoreOrderBillLog>().in("red_status", "01").isNull("bill_no"));
        if(list2.isEmpty()) return;
        PubFun.batchProcessing(50, list2, this::updateRedData);
    }
    @Transactional
    public void billUpload(){
        // 节假日判断
//        LocalDateTime dateNow = LocalDateTime.now();
//        LocalDateTime startDate = LocalDateTime.of(2025, 1, 26, 23, 0, 0);   // 0点
//        LocalDateTime endDate = LocalDateTime.of(2025, 2, 1, 0, 0, 0);
//        if((!dateNow.isBefore(startDate) && !dateNow.isAfter(endDate))) return;
        List<FsStoreOrderBillLog> list = fsStoreOrderBillLogService.list(new QueryWrapper<FsStoreOrderBillLog>().eq("upload_api", 0));
        if(list.isEmpty()) return;
        list.forEach(e -> NuonuoUtils.requestBilling(e.getOrderNo(), e.getPayerName(), e.getPayerTaxNo(), e.getOrderAmount(), e.getRemark()));
        list.forEach(e -> e.setUploadApi(1));
        fsStoreOrderBillLogService.updateBatchById(list);
    }

    // 冲红信息同步
    public void updateRedData(List<FsStoreOrderBillLog> list){
        List<InvoiceResultVo> invoiceResultList = NuonuoUtils.queryInvoiceResult(PubFun.listToNewList(list, FsStoreOrderBillLog::getOrderNo));
        Map<String, InvoiceResultVo> invoiceResultMap = PubFun.listToMapByGroupObject(invoiceResultList, InvoiceResultVo::getOrderNo);
        list.stream().filter(e -> invoiceResultMap.containsKey(e.getOrderNo())).forEach(e -> e.setJson(JSON.toJSONString(invoiceResultMap.get(e.getOrderNo()))));

        list.forEach(e -> {
            List<InvoiceRedVo> invoiceRedVoList = NuonuoUtils.queryInvoiceRedConfirm(e.getInvoiceNo());
            if(invoiceRedVoList.isEmpty()) return;
            InvoiceRedVo invoiceRedVo = invoiceRedVoList.get(0);
            e.setBillUuid(invoiceRedVo.getBillUuid());
            e.setBillNo(invoiceRedVo.getBillNo());
            e.setRedStatus(invoiceRedVo.getBillStatus());
        });
        fsStoreOrderBillLogService.updateBatchById(list);
        rollbackOrderBill(list);
    }
    // 开票信息同步
    public void updateData(List<FsStoreOrderBillLog> list){
        List<InvoiceResultVo> invoiceResultList = NuonuoUtils.queryInvoiceResult(PubFun.listToNewList(list, FsStoreOrderBillLog::getOrderNo));
        Map<String, InvoiceResultVo> invoiceResultMap = PubFun.listToMapByGroupObject(invoiceResultList, InvoiceResultVo::getOrderNo);
        list.stream().filter(e -> invoiceResultMap.containsKey(e.getOrderNo())).forEach(e -> {
            InvoiceResultVo vo = invoiceResultMap.get(e.getOrderNo());
            e.setSerialNo(vo.getSerialNo());
            e.setInvoiceCode(vo.getInvoiceCode());
            e.setInvoiceNo(vo.getInvoiceNo());
            e.setAllElectronicInvoiceNumbe(vo.getAllElectronicInvoiceNumbe());
            e.setInvoiceKind(vo.getInvoiceKind());
            e.setOrderAmount(BigDecimal.valueOf(Double.parseDouble(vo.getOrderAmount())));
            e.setPayerName(vo.getPayerName());
            e.setPayerTaxNo(vo.getPayerTaxNo());
            e.setAddress(vo.getAddress());
            e.setTelephone(vo.getTelephone());
            e.setPaperPdfUrl(vo.getPaperPdfUrl());
            e.setInvoiceTime(vo.getInvoiceTime());
            e.setPictureUrl(vo.getPictureUrl());
            e.setPdfUrl(vo.getPdfUrl());
            e.setFailCause(vo.getFailCause());
            e.setStatusMsg(vo.getStatusMsg());
            e.setStatus(Integer.parseInt(vo.getStatus()));
            e.setImgUrls(vo.getImgUrls());
            e.setRemark(vo.getRemark());
            e.setJson(JSON.toJSONString(vo));
        });
        fsStoreOrderBillLogService.updateBatchById(list);
        // 筛选开票异常列表
        rollbackOrderBill(list.stream().filter(e -> e.getStatus() != 2).collect(Collectors.toList()));
    }
    //退回订单开票金额
    public void rollbackOrderBill(List<FsStoreOrderBillLog> failedList){
        if(failedList.isEmpty()) return;
        Map<Long, List<FsStoreOrderBillLog>> logListMap = PubFun.listToMapByGroupList(failedList, FsStoreOrderBillLog::getOrderId);
        List<FsStoreOrder> orderList = fsStoreOrderService.selectFsStoreOrderByOrderIdIn(PubFun.listToNewList(failedList, FsStoreOrderBillLog::getOrderId));
        // 返还开票金额并且保存
        orderList.stream().filter(e -> logListMap.containsKey(e.getOrderId())).forEach(e -> {
            List<FsStoreOrderBillLog> logs = logListMap.get(e.getOrderId());
            BigDecimal total = logs.stream().map(FsStoreOrderBillLog::getOrderAmount).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
            e.setBillPrice(e.getBillPrice().subtract(total));
            fsStoreOrderService.updateFsStoreOrder(e);
        });
    }


}
