package com.ecep.contract.service.tasker;

import com.ecep.contract.MessageHolder;
import com.ecep.contract.cloud.rk.CloudRkService;
import com.ecep.contract.cloud.rk.ctx.CloudRkCtx;
import com.ecep.contract.constant.CloudServiceConstant;
import com.ecep.contract.ds.company.model.Company;
import com.ecep.contract.ds.company.service.CompanyService;
import com.ecep.contract.ds.other.model.CloudRk;
import com.ecep.contract.ui.Tasker;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;

import java.time.LocalDateTime;

/**
 *
 */
public class CompanyRkUpdateTasker extends Tasker<Object> implements WebSocketServerTasker {
    private static final Logger logger = LoggerFactory.getLogger(CompanyRkUpdateTasker.class);
    @Setter
    private Company company;
    @Setter
    private CloudRkService cloudRkService;

    @Override
    public void init(JsonNode argsNode) {
        int companyId = argsNode.get(0).asInt();
        company = getCachedBean(CompanyService.class).getById(companyId);
    }

    @Override
    protected Object execute(MessageHolder holder) throws Exception {
        holder.debug("1. 从 " + CloudServiceConstant.RK_NAME + " 更新...");
        try {
            cloudRkService = getCachedBean(CloudRkService.class);
        } catch (BeansException e) {
            throw new RuntimeException("服务未启用");
        }
        CloudRk cloudRk = cloudRkService.getOrCreateCloudRk(company);
        if (cloudRk == null) {
            throw new RuntimeException("无法创建或获取 CloudRk 对象");
        }

        try {
            CloudRkCtx cloudRkCtx = new CloudRkCtx();
            if (cloudRkCtx.syncCompany(company, cloudRk, holder)) {
                holder.info("更新完成");
            }
        } catch (Exception e) {
            String message = e.getMessage();
            if (message.length() > 50) {
                message = message.substring(0, 50);
            }
            cloudRk.setDescription(message);
        } finally {
            cloudRk.setLatestUpdate(LocalDateTime.now());
            try {
                cloudRkService.save(cloudRk);
            } catch (Exception e) {
                holder.error("保存 CloudRk 错误: " + cloudRk.getDescription());
            }
        }
        return null;
    }
}
