package com.ecep.contract.cloud.u8;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

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.CloudInfo;
import com.ecep.contract.model.CloudYu;
import com.ecep.contract.ui.Tasker;

import lombok.Setter;

/**
 * 数据迁移任务，从CloudInfo迁移到CloudYu
 */
public class DateTransferTask extends Tasker<Object> {
    private static final Logger logger = LoggerFactory.getLogger(DateTransferTask.class);
    @Setter
    private YongYouU8Service yongYouU8Service;

    public DateTransferTask() {
        updateTitle("用友U8系统-数据迁移任务");
    }

    YongYouU8Service getYongYouU8Service() {
        if (yongYouU8Service == null) {
            yongYouU8Service = SpringApp.getBean(YongYouU8Service.class);
        }
        return yongYouU8Service;
    }

    @Override
    protected Object execute(MessageHolder holder) throws Exception {
        YongYouU8Service u8Service = null;
        try {
            u8Service = getYongYouU8Service();
        } catch (BeansException e) {
            logger.error("获取用友U8服务失败", e);
            holder.error("获取用友U8服务失败");
            return null;
        }

        AtomicInteger counter = new AtomicInteger(0);
        logger.info("开始数据迁移任务...");
        Iterable<CloudInfo> cloudInfos = u8Service.findAllCloudYu();

        // 计算总数
        int total = 0;
        for (@SuppressWarnings("unused")
        CloudInfo info : cloudInfos) {
            total++;
        }
        holder.debug("总共需要迁移的数据量: " + total + " 条");

        // 重新获取Iterable以进行遍历
        cloudInfos = u8Service.findAllCloudYu();

        for (CloudInfo v : cloudInfos) {
            if (isCancelled()) {
                holder.info("迁移任务已取消");
                return null;
            }

            MessageHolder sub = holder.sub(counter.get() + "/" + total + ">");
            try {
                sync(v, sub);
            } catch (Exception e) {
                sub.error("迁移失败: " + e.getMessage());
                logger.error("迁移数据失败", e);
            }

            // 更新进度
            updateProgress(counter.incrementAndGet(), total);
        }

        holder.info("数据迁移任务完成");
        return null;
    }

    private void sync(CloudInfo v, MessageHolder holder) {
        YongYouU8Service u8Service = getYongYouU8Service();
        CloudYu cloudYu = u8Service.getOrCreateCloudYu(v);

        if (copyTo(v, cloudYu)) {
            u8Service.save(cloudYu);
            holder.info("成功迁移数据: " + v.getCloudId());
        } else {
            holder.debug("数据未变更，无需迁移: " + v.getCloudId());
        }
    }

    boolean copyTo(CloudInfo v, CloudYu cloudRk) {
        boolean modified = false;
        if (!Objects.equals(cloudRk.getLatestUpdate(), v.getLatestUpdate())) {
            cloudRk.setLatestUpdate(v.getLatestUpdate());
            modified = true;
        }
        if (!Objects.equals(cloudRk.getCompany(), v.getCompany())) {
            cloudRk.setCompany(v.getCompany());
            modified = true;
        }
        return modified;
    }
}