package com.ecep.contract.ds.other.controller;

import java.util.concurrent.atomic.AtomicInteger;

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 com.ecep.contract.MessageHolder;
import com.ecep.contract.cloud.u8.ctx.InventoryCtx;
import com.ecep.contract.ds.other.service.InventoryService;
import com.ecep.contract.model.Inventory;
import com.ecep.contract.service.tasker.WebSocketServerTasker;
import com.ecep.contract.ui.Tasker;
import com.ecep.contract.vo.InventoryVo;
import com.fasterxml.jackson.databind.JsonNode;

import lombok.Setter;

public class InventorySyncTask extends Tasker<Object> implements WebSocketServerTasker {
    private InventoryCtx inventoryCtx;
    @Setter
    private Inventory inventory;

    public InventoryService getInventoryService() {
        return getCachedBean(InventoryService.class);
    }

    @Override
    public void init(JsonNode argsNode) {
        int inventoryId = argsNode.get(0).asInt();
        inventory = getInventoryService().getById(inventoryId);
    }

    @Override
    protected Object execute(MessageHolder holder) throws Exception {
        if (inventory == null) {
            holder.error("库存不存在");
            return null;
        }
        updateProgress(0, 1000);

        inventoryCtx = new InventoryCtx(this);
        inventoryCtx.initializeRepository(holder);

        if (inventoryCtx.syncInventory(inventory, holder)) {
            getInventoryService().save(inventory);
            holder.info("库存数据同步成功：" + inventory.getCode());
        }

        updateProgress(1000, 1000);
        holder.info("库存同步任务完成！");
        return null;
    }

}
