package com.ecep.contract.ds.vendor.task;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.stream.Collectors;

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 org.springframework.util.StringUtils;

import com.ecep.contract.MessageHolder;
import com.ecep.contract.ds.contract.tasker.ContractRepairComm;
import com.ecep.contract.ds.vendor.service.CompanyVendorService;
import com.ecep.contract.model.CompanyVendor;
import com.ecep.contract.ui.Tasker;

/**
 * 对所有供应商进行核验
 */
public class VendorVerifyAllTasker extends Tasker<Object> {

    private ContractRepairComm comm = new ContractRepairComm();

    @Override
    protected Object execute(MessageHolder holder) {
        updateTitle("遍历核验所有供应商");
        Pageable pageRequest = PageRequest.ofSize(200);
        AtomicInteger counter = new AtomicInteger(0);
        Specification<CompanyVendor> spec = null;

        CompanyVendorService vendorService = getBean(CompanyVendorService.class);
        long total = vendorService.count(spec);
        while (true) {
            if (isCancelled()) {
                break;
            }

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

            for (CompanyVendor vendor : page) {
                if (isCancelled()) {
                    break;
                }
                MessageHolder subHolder = holder.sub(counter.get() + " / " + total + "> #" + vendor.getId() + "> ");

                List<String> meesages = new ArrayList<>();
                MessageHolderImpl messageHolder = new MessageHolderImpl() {
                    @Override
                    public void addMessage(Level level, String message) {
                        if (level.intValue() > Level.INFO.intValue()) {
                            meesages.add(message);
                        }
                    }
                };
                try {
                    vendorService.verify(vendor, messageHolder);

                } catch (Exception e) {
                    subHolder.error(e.getMessage());
                    e.printStackTrace();
                }

                String msg = meesages.stream().collect(Collectors.joining(", "));
                if (StringUtils.hasText(msg)) {
                    subHolder.error(msg);
                }
            }
            if (!page.hasNext()) {
                break;
            }
            pageRequest = page.nextPageable();
        }
        return null;
    }

}
