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

import java.time.LocalDate;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;

import com.ecep.contract.MessageHolder;
import com.ecep.contract.ds.company.service.CompanyService;
import com.ecep.contract.ds.contract.tasker.ContractVerifyComm;
import com.ecep.contract.model.Company;
import com.ecep.contract.model.Contract;
import com.ecep.contract.ui.Tasker;

import lombok.Getter;
import lombok.Setter;

public class CompanyVerifyTasker extends Tasker<Object> {
    @Setter
    private CompanyService companyService;
    @Getter
    @Setter
    private Company company;


    ContractVerifyComm comm = new ContractVerifyComm();
    AtomicBoolean verified = new AtomicBoolean(true);

    public CompanyService getCompanyService() {
        if (companyService == null) {
            companyService = getBean(CompanyService.class);
        }
        return companyService;
    }

    @Override
    public Object call() throws Exception {
        comm.setVerifyCompanyPath(false);
        comm.setVerifyCompanyStatus(false);
        comm.setVerifyCompanyCredit(false);
        return execute(new MessageHolderImpl() {
            @Override
            public void addMessage(Level level, String message) {
                super.addMessage(level, message);
                if (level.intValue() > Level.INFO.intValue()) {
                    verified.set(false);
                }
            }
        });
    }

    @Override
    protected Object execute(MessageHolder holder) throws Exception {
        updateTitle("验证企业是否符合合规要求");

        verify(company, holder);

        if (verified.get()) {
            updateMessage(Level.CONFIG, "合规验证通过");
        } else {
            updateMessage(Level.SEVERE, "合规验证不通过");
        }
        return null;
    }

    /**
     * 核验公司名下的所有合同
     *
     * @param company 公司
     * @param holder  输出
     */
    private void verify(Company company, MessageHolder holder) {
        LocalDate now = LocalDate.now();
        getCompanyService().verifyEnterpriseStatus(company, now, holder::info);

        // 验证所有的合同
        List<Contract> list = comm.getContractService().findAllByCompany(company);
        if (list.isEmpty()) {
            holder.debug("!没有相关合同!");
            return;
        }
        holder.debug("检索到相关合同 " + list.size() + " 个");
        AtomicInteger counter = new AtomicInteger(0);
        long total = list.size();
        for (Contract contract : list) {
            holder.debug("核验合同：" + contract.getCode() + ", " + contract.getName());
            comm.verify(company, contract, holder.sub("-- "));
            updateProgress(counter.incrementAndGet(), total);
        }
        updateProgress(1, 1);
    }
}
