package com.ecep.contract.cloud.rk;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import org.hibernate.Hibernate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;

import com.ecep.contract.MessageHolder;
import com.ecep.contract.SpringApp;
import com.ecep.contract.cloud.rk.ctx.CloudRkCtx;
import com.ecep.contract.constant.CloudServiceConstant;
import com.ecep.contract.ds.contract.service.ContractService;
import com.ecep.contract.model.CloudRk;
import com.ecep.contract.model.Company;
import com.ecep.contract.ui.Tasker;

/**
 * 集团相关方平台同步任务
 */
public class CloudRkSyncTask extends Tasker<Object> {
    private static final Logger logger = LoggerFactory.getLogger(CloudRkSyncTask.class);

    private ContractService contractService;

    @Override
    protected Object execute(MessageHolder holder) throws Exception {
        updateTitle("集团相关方平台");

        CloudRkCtx cloudRkCtx = null;
        CloudRkService service = null;
        try {
            cloudRkCtx = new CloudRkCtx();
            service = SpringApp.getBean(CloudRkService.class);
            cloudRkCtx.setCloudRkService(service);
        } catch (BeansException e) {
            holder.error("没有找到 " + CloudServiceConstant.RK_NAME + " 服务");
            return null;
        }

        long total = service.countNeedUpdate();
        if (total == 0) {
            holder.info("没有需要更新");
            return null;
        }

        AtomicInteger counter = new AtomicInteger(0);
        holder.info("统计需要更新的 " + total + " 条");

        try {
            // 每次获取100条记录
            while (!isCancelled()) {
                List<CloudRk> needUpdate = service.findNeedUpdate();
                if (needUpdate.isEmpty()) {
                    holder.info("处理完成");
                    break;
                }
                for (CloudRk cloudRk : needUpdate) {
                    if (isCancelled()) {
                        break;
                    }
                    MessageHolder subHolder = holder.sub(counter.get() + " / " + total + ">");
                    // fixed lazy
                    Company company = cloudRk.getCompany();
                    if (company == null) {
                        subHolder.error("数据不完整，没有关联公司");
                        break;
                    }
                    if (!Hibernate.isInitialized(company)) {
                        company = getCompanyService().findById(company.getId());
                        cloudRk.setCompany(company);
                    }
                    if (cloudRk.isAutoUpdate()) {
                        LocalDate date = LocalDate.now().minusYears(3);
                        long count = getContractService().findAllByCompany(company).stream()
                                .filter(c -> c.getSetupDate() != null)
                                .filter(c -> c.getSetupDate().isAfter(date))
                                .count();
                        if (count == 0) {
                            holder.info("公司：" + company.getName() + " 没有3年以上的合同, 取消自动更新");
                            cloudRk.setAutoUpdate(false);
                        }
                    }
                    try {
                        cloudRk.setDescription("");
                        if (cloudRkCtx.syncCompany(company, cloudRk, subHolder)) {

                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    } finally {
                        cloudRk.setLatestUpdate(LocalDateTime.now());
                        service.save(cloudRk);
                    }
                    // updateProgress(counter.incrementAndGet(), total);
                }
            }

            if (isCancelled()) {
                updateMessage("Cancelled");
            }
        } catch (Exception e) {
            logger.error("运行至 {}/{} 时，发生错误中断", counter.get(), total, e);
        }
        // updateProgress(1, 1);
        return null;
    }

    public CompletableFuture<Void> delay(int second, Executor executor) {
        CompletableFuture<Void> future = new CompletableFuture<>();

        long until = System.currentTimeMillis() + second * 1000L;
        String title = "";
        AtomicReference<Runnable> reference = new AtomicReference<>();
        Runnable runnable = () -> {
            long let = until - System.currentTimeMillis();
            if (let < 0) {
                System.out.println("complete @" + Thread.currentThread().getName());
                future.complete(null);
            } else {
                // 再次调度
                executor.execute(reference.get());
                updateTitle(title + " 延时 " + ((int) let / 1000) + "秒");
            }
        };
        reference.set(runnable);
        // 第一次调度
        executor.execute(runnable);
        return future;
    }

    ContractService getContractService() {
        if (contractService == null) {
            contractService = getBean(ContractService.class);
        }
        return contractService;
    }
}
