package com.ecep.contract.service.tasker;

import java.time.LocalDate;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import com.ecep.contract.MessageHolder;
import com.ecep.contract.ds.contract.service.ContractService;
import com.ecep.contract.ds.contract.tasker.ContractVerifyComm;
import com.ecep.contract.ds.company.model.Company;
import com.ecep.contract.ds.contract.model.Contract;
import com.ecep.contract.ui.Tasker;
import com.fasterxml.jackson.databind.JsonNode;

import lombok.Getter;
import lombok.Setter;

public class CompanyVerifyTasker extends Tasker<Object> implements WebSocketServerTasker {
    @Getter
    @Setter
    private Company company;
    @Getter
    @Setter
    boolean passed = false;

    ContractVerifyComm comm = new ContractVerifyComm();

    public ContractService getContractService() {
        return getCachedBean(ContractService.class);
    }

    /**
     * 核验公司名下的所有合同
     */
    @Override
    public void init(JsonNode argsNode) {
        int companyId = argsNode.get(0).asInt();
        company = getCompanyService().getById(companyId);
        comm.setVerifyCompanyPath(false);
        comm.setVerifyCompanyStatus(false);
        comm.setVerifyCompanyCredit(false);
    }

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

        verify(company, holder);

        if (passed) {
            holder.info("合规验证通过");
        } else {
            holder.error("合规验证不通过");
        }

        updateProperty("passed", passed);
        return null;
    }

    private void verify(Company company, MessageHolder holder) {
        LocalDate now = LocalDate.now();
        if (getCompanyService().verifyEnterpriseStatus(company, now, holder)) {
            passed = false;
        }

        // 验证所有的合同
        List<Contract> list = 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());
            if (!comm.verify(company, contract, holder.sub("-- "))) {
                passed = false;
            }
            updateProgress(counter.incrementAndGet(), total);
        }
        updateProgress(1, 1);
    }
}
