package com.sw.mes.sap.controller;

import cc.cczn.matrix.common.monitor.entry.MatrixEntry;
import cc.cczn.matrix.common.monitor.entry.NodeType;
import cc.cczn.matrix.commons.tasks.queue.Task;
import cc.cczn.matrix.commons.tasks.queue.block.LinkedBlockDataQueue;
import com.alibaba.fastjson.JSON;
import com.sw.mes.base.factory.material.dao.MaterialModelDao;
import com.sw.mes.base.factory.material.entity.MaterialModel;
import com.sw.mes.base.factory.material.service.MaterialModelService;
import com.sw.mes.base.global.GlobalSwitch;
import com.sw.mes.base.global.GlobalSwitchNamespace;
import com.sw.mes.base.global.SwitchConfig;
import com.sw.mes.core.api.system.StoreFeignClients;
import com.sw.mes.core.dto.store.WarehouseMaterialBo;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.sap.task.MaterialToStoreHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;


/**
 * 物料数据全量同步到线边仓
 *
 * @Author：wanjia
 * @Date：2024/2/4 15:03
 */
@RestController
@RequestMapping("/sync")
public class MaterialSyncController {

    private static final Logger logger = LoggerFactory.getLogger(MaterialSyncController.class);

    @Autowired
    private MaterialModelDao materialModelDao;


    @Autowired
    private LinkedBlockDataQueue storeSyncQueue;

    @Autowired
    private StoreFeignClients storeFeignClients;


    @RequestMapping("/material_to_store/{pageSize}")
    public void run(@PathVariable("pageSize") int pageSize) {
        logger.error("start sync data from material tp store.....");
        MaterialToStoreHandler.total.set(0);
        RequestPage page = new RequestPage();
        page.setPage(1);
        page.setRows(pageSize);
        Page<MaterialModel> result = materialModelDao.findAll(PageUtil.createPageable(page));
        if (null == result || CollectionUtils.isEmpty(result.getContent())) {
            logger.error("get result == null from database...");
        }
        //全量的数据
        int totalPages = result.getTotalPages();
        int count = 0;
        for (int i = 0; i <= totalPages; i++) {
            RequestPage p = new RequestPage();
            p.setPage(i + 1);
            p.setRows(pageSize);
            Page<MaterialModel> tmpResult = materialModelDao.findAll(PageUtil.createPageable(p));
            for (MaterialModel model : tmpResult) {
                Task<MaterialModel> task = new Task<>();
                task.setData(model);
                try {
                    storeSyncQueue.submitTask(task, 5, TimeUnit.SECONDS);
                    count++;
                } catch (Exception e) {
                    logger.error("submit error", e);
                }
            }
            logger.error("已经提交第" + (i + 1) + "批数据...已经提交共：" + count + "条数据...");
        }
    }


    @RequestMapping("/test_sync")
    public void testSync() {
        MatrixEntry.startEntry("test_sync");
        RequestPage page = new RequestPage();
        page.setPage(1);
        page.setRows(10);
        MatrixEntry.entry("findAll", NodeType.METHOD);
        Page<MaterialModel> result = materialModelDao.findAll(PageUtil.createPageable(page));
        MatrixEntry.exit();
        for (MaterialModel materialModel : result.getContent()) {
            ArrayList<WarehouseMaterialBo> warehouseMaterialBos = new ArrayList<>();
            WarehouseMaterialBo bo = new WarehouseMaterialBo();
            bo.setMaterialId(materialModel.getId().longValue());
            bo.setMaterialCode(materialModel.getCode());
            bo.setMaterialName(materialModel.getName());
            warehouseMaterialBos.add(bo);
            MatrixEntry.entry("syncMaterial", NodeType.REMOTE_CALL);
            Result r = storeFeignClients.syncMaterial(warehouseMaterialBos);
            MatrixEntry.exit();
            if (r.getCode() == 200) {
                System.out.println("---------ok----------");
            }
        }
        MatrixEntry.endEntry();
    }

    @RequestMapping("/switch/{namespace}/{key}")
    public String checkGlobalSwitch(@PathVariable("namespace") String namespace, @PathVariable("key") String key) {
        boolean val = GlobalSwitch.enable(namespace, key, false);
        SwitchConfig config = GlobalSwitch.switchConfig(namespace, key, false);
        return JSON.toJSONString(config);
    }
}
