package com.ecep.contract.service.tasker;

import org.hibernate.Hibernate;
import org.springframework.util.StringUtils;

import com.ecep.contract.MessageHolder;
import com.ecep.contract.ds.company.service.CompanyService;
import com.ecep.contract.ds.customer.service.CustomerService;
import com.ecep.contract.ds.company.model.Company;
import com.ecep.contract.ds.customer.model.CompanyCustomer;
import com.ecep.contract.ui.Tasker;
import com.fasterxml.jackson.databind.JsonNode;

/**
 * 客户文件重建任务器
 * 用于重建客户相关文件，同步文件系统和数据库记录
 */
public class CompanyCustomerRebuildFilesTasker extends Tasker<Object> implements WebSocketServerTasker {

    private CompanyCustomer customer;

    CustomerService getCompanyCustomerService() {
        return getCachedBean(CustomerService.class);
    }

    @Override
    public void init(JsonNode argsNode) {
        int customerId = argsNode.get(0).asInt();
        customer = getCompanyCustomerService().getById(customerId);
    }

    void setFilesUpdated(boolean filesUpdated) {
        updateProperty("filesUpdated", filesUpdated);
    }

    @Override
    protected Object execute(MessageHolder holder) throws Exception {
        updateTitle("重建客户文件");
        updateProgress(0, 100);

        if (customer == null) {
            holder.error("客户不存在");
            return false;
        }

        if (!StringUtils.hasText(customer.getPath())) {
            holder.error("客户路径未设置，无法重建文件");
            updateProgress(100, 100);
            return false;
        }

        Company company = customer.getCompany();
        if (!Hibernate.isInitialized(company)) {
            company = getCachedBean(CompanyService.class).getById(company.getId());
        }

        try {
            holder.info("开始重建客户文件：" + company.getName());
            holder.info("客户路径：" + customer.getPath());

            boolean result = getCompanyCustomerService().reBuildingFiles(customer, holder);

            if (result) {
                holder.info("客户文件重建成功");
                setFilesUpdated(true);
            } else {
                holder.info("客户文件重建完成，但没有更新任何文件");
                setFilesUpdated(false);
            }

            updateProgress(100, 100);
            return result;
        } catch (Exception e) {
            holder.error("客户文件重建失败：" + e.getMessage());
            updateProgress(100, 100);
            throw e;
        }
    }
}