package com.ecep.contract.ds.contract.tasker;

import java.time.Instant;
import java.time.LocalDate;

import org.springframework.beans.BeansException;

import com.ecep.contract.MessageHolder;
import com.ecep.contract.cloud.u8.YongYouU8Service;
import com.ecep.contract.cloud.u8.ctx.CustomerCtx;
import com.ecep.contract.cloud.u8.ctx.VendorCtx;
import com.ecep.contract.constant.CloudServiceConstant;
import com.ecep.contract.model.CloudYu;
import com.ecep.contract.model.Company;

import lombok.Getter;
import lombok.Setter;

public class ContractRepairByCompanyTask extends AbstContractRepairTasker {
    @Getter
    @Setter
    private Company company;
    @Setter
    private YongYouU8Service yongYouU8Service;


    @Getter
    boolean repaired = false;

    @Override
    protected void repair(MessageHolder holder) {
        updateTitle("同步修复 " + company.getName() + " 下的所有合同");
        try {
            yongYouU8Service = getBean(YongYouU8Service.class);
        } catch (BeansException e) {
            holder.warn("未启用 " + CloudServiceConstant.U8_NAME + " 服务");
            return;
        }

        CloudYu cloudYu = yongYouU8Service.getOrCreateCloudYu(company);
        if (cloudYu == null) {
            holder.error("无法创建或获取 CloudYu 对象");
            return;
        }

        try {
            VendorCtx vendorCtx = new VendorCtx();
            vendorCtx.from(contractCtx);
            if (vendorCtx.syncVendor(company, holder)) {
                cloudYu.setVendorUpdateDate(LocalDate.now());
                repaired = true;
            }

            CustomerCtx customerCtx = new CustomerCtx();
            customerCtx.from(contractCtx);
            if (customerCtx.syncCustomer(company, holder)) {
                cloudYu.setCustomerUpdateDate(LocalDate.now());
                repaired = true;
            }

            cloudYu.setCloudLatest(Instant.now());
            cloudYu.setExceptionMessage("");
        } catch (Exception e) {
            cloudYu.setExceptionMessage(e.getMessage());
        } finally {
            cloudYu.setLatestUpdate(Instant.now());
            yongYouU8Service.save(cloudYu);
        }
    }
}
