package com.ecep.contract.cloud.u8.ctx;

import static com.ecep.contract.SpringApp.getBean;

import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;

import org.springframework.util.StringUtils;

import com.ecep.contract.MessageHolder;
import com.ecep.contract.ds.company.service.InvoiceService;
import com.ecep.contract.model.Invoice;

import lombok.Setter;

public class InvoiceCtx extends AbstractYongYouU8Ctx {
    @Setter
    private InvoiceService invoiceService;

    InvoiceService getInvoiceService() {
        if (invoiceService == null) {
            invoiceService = getBean(InvoiceService.class);
        }
        return invoiceService;
    }

    public boolean updateInvoiceByNumber(Supplier<Invoice> getter, Consumer<Invoice> setter, String invoiceNumber,
            MessageHolder holder, String topic) {
        // TODO 从U8系统中获取数据
        Invoice invoice = null;
        if (StringUtils.hasText(invoiceNumber)) {
            invoice = getInvoiceService().findByCode(invoiceNumber);
            if (invoice == null) {
                invoice = new Invoice();
                invoice.setCode(invoiceNumber);
                invoice = getInvoiceService().save(invoice);
            }
        }
        if (invoice == null) {
            setter.accept(null);
            holder.warn("无效" + topic + "：" + invoiceNumber);
            return true;
        } else {
            if (!Objects.equals(getter.get(), invoice)) {
                setter.accept(invoice);
                holder.info(topic + "修改为: " + invoice.getCode());
                return true;
            }
        }
        return false;
    }
}
