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

import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;

import com.ecep.contract.MessageHolder;
import com.ecep.contract.ds.company.service.CompanyFileService;
import com.ecep.contract.model.Company;
import com.ecep.contract.ui.Tasker;

/**
 * 对所有公司的文件进行重置
 */
public class CompanyFilesRebuildTasker extends Tasker<Object> {
    private CompanyFileService companyFileService;

    public CompanyFilesRebuildTasker() {
        updateTitle("合同文件重置");
    }

    @Override
    protected Object execute(MessageHolder holder) throws Exception {
        Pageable pageRequest = PageRequest.ofSize(200);
        AtomicInteger counter = new AtomicInteger(0);
        Specification<Company> spec = null;
//        Specification<Contract> spec = (root, query, cb) -> {
//            return cb.greaterThan(root.get("created"), Instant.now().minusSeconds(TimeUnit.DAYS.toSeconds(360)));
//        };
        updateTitle("遍历所有公司，对每个可以公司的文件进行“重置”操作");
        long total = getCompanyService().count(spec);
        while (true) {
            if (isCancelled()) {
                break;
            }


            Page<Company> page = getCompanyService().findAll(spec, pageRequest);
            if (page.isEmpty()) {
                break;
            }

            for (Company company : page) {
                if (isCancelled()) {
                    break;
                }

                String prefix = counter.get() + " / " + total + "> " + company.getName() + " #" + company.getId() + "> ";
                getCompanyFileService().reBuildingFiles(company, holder.sub(prefix)::info);

                updateProgress(counter.incrementAndGet(), total);
            }
            if (!page.hasNext()) {
                break;
            }
            pageRequest = page.nextPageable();
        }

        return super.call();
    }


    private CompanyFileService getCompanyFileService() {
        if (companyFileService == null) {
            companyFileService = getBean(CompanyFileService.class);
        }
        return companyFileService;
    }
}
