package cn.iocoder.yudao.module.pms.job.sap;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotsapstock.IotSapStockDO;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.saporg.dto.SapOrgRespDTO;
import com.sap.conn.jco.JCoDestination;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class SyncSapStockContext {
    public JCoDestination destination;
    public List<IotSapStockDO> existStocks;
    public List<SapOrgRespDTO> storageLocations;
    public List<SapOrgRespDTO> factories;
    public List<DeptRespDTO> depts;

    // 映射关系
    public Map<String, Long> factoryIdPair = new HashMap<>();
    public Map<String, String> factoryNamePair = new HashMap<>();
    public Map<String, Long> storageLocationIdPair = new HashMap<>();
    public Map<Long, String> stockLocationCodeIdPair = new HashMap<>();
    public Map<String, Long> locationCodeDeptIdPair = new HashMap<>();
    public Map<String, String> stockLocationNamePair = new HashMap<>();

    boolean valid = false;

    SyncSapStockContext invalid() {
        SyncSapStockContext context = new SyncSapStockContext();
        valid = false;
        return context;
    }

    boolean isValid() {
        return valid && destination != null;
    }

    void buildMappings() {
        // 工厂映射
        factories.forEach(factory -> {
            factoryIdPair.put(factory.getFactoryCode(), factory.getId());
            factoryNamePair.put(factory.getFactoryCode(), factory.getFactoryName());
        });

        // 库存地点映射
        storageLocations.forEach(location -> {
            String uniqueKey = StrUtil.join("-", location.getFactoryCode(), location.getStorageLocationCode());
            stockLocationCodeIdPair.put(location.getId(), uniqueKey);
            storageLocationIdPair.put(uniqueKey, location.getId());
            stockLocationNamePair.put(uniqueKey, location.getStorageLocationName());
        });

        // 部门映射
        depts.forEach(dept -> {
            Set<Long> stockLocationIds = dept.getStockLocationIds();
            if (CollUtil.isNotEmpty(stockLocationIds)) {
                stockLocationIds.forEach(locationId -> {
                    if (stockLocationCodeIdPair.containsKey(locationId)) {
                        String uniqueKey = stockLocationCodeIdPair.get(locationId);
                        locationCodeDeptIdPair.put(uniqueKey, dept.getId());
                    }
                });
            }
        });

        valid = true;
    }
}
