package com.wms_main.app;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wms_main.dao.ITAppConfigService;
import com.wms_main.dao.ITAppGoodsService;
import com.wms_main.dao.ITAppLocationService;
import com.wms_main.model.po.TAppConfig;
import com.wms_main.model.po.TAppGoods;
import com.wms_main.model.po.TAppLocation;
import com.wms_main.repository.utils.StringUtils;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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

/**
 * Application 共享
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class AppCommon {
    private final static Integer MIN_DEPTH = 1;
    private final static Integer MAX_DEPTH = 3;
    /**
     * 配置服务
     */
    private final ITAppConfigService appConfigService;
    private final ITAppLocationService appLocationService;
    private final ITAppGoodsService appGoodsService;
    /**
     * 配置map
     */
    public final Map<String, String> configMap = new HashMap<>();
    /**
     * 库位map
     */
    public final Map<String, TAppLocation> instantLocationMap = new HashMap<>();
    /**
     * 物料信息Map
     */
    private final Map<String, TAppGoods> instantGoodsMap = new HashMap<>();

    /**
     * 根据key获取值
     * @param key 键
     * @return 值
     */
    public String getConfigByKey(String key) {
        if (configMap.isEmpty()) {
            if (!initConfigMap()) {
                log.error("配置初始化失败，请尝试重启程序。");
                return "";
            }
        }
        return configMap.get(key);
    }

    /**
     * 更新配置
     * @return 更新结果
     */
    public boolean initConfigMap() {
        configMap.clear();// 清除配置值
        try {
            // 获取到所有的配置
            List<TAppConfig> configList = appConfigService.list();
            if (!configList.isEmpty()) {
                for (TAppConfig appConfig : configList) {
                    configMap.put(appConfig.getConfigKey(), appConfig.getConfigValue());
                    log.info("导入系统配置成功---{}：{}", appConfig.getConfigName(), appConfig.getConfigValue());
                }
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 根据库位id获取库位信息
     * @param locationId 库位id
     * @return 库位详情
     */
    public TAppLocation getInstantLocationByLocationId(String locationId) {
        if (instantLocationMap.isEmpty()) {
            if (!initInstantLocationMap()) {
                log.error("库位缓存失败，请尝试重启程序。");
                return null;
            }
        }
        return instantLocationMap.get(locationId);
    }

    /**
     * 初始化库位缓存map
     * @return 缓存结果
     */
    public boolean initInstantLocationMap() {
        instantLocationMap.clear();
        try {
            // 获取到所有的配置
            List<TAppLocation> locationList = appLocationService.list();
            if (!locationList.isEmpty()) {
                for (TAppLocation appLocation : locationList) {
                    instantLocationMap.put(appLocation.getLocationId(), appLocation);
                }
            }
            log.info("库位缓存成功。");
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    
    /**
     * 根据库位id获取排列层所有深度的库位信息列表
     * @param locationId 库位id
     * @return 库位详情列表
     */
    public List<TAppLocation> getLocationListByLocationId(String locationId) {
        List<TAppLocation> resList = new ArrayList<>();
        List<String> strList = List.of(locationId.split("-")).subList(0, 3);
        for (int depth = MIN_DEPTH; depth <= MAX_DEPTH; ++depth) {
            String queryLocationId = String.join("-", strList) + String.format("-%02d", depth);
            TAppLocation tempLocation = getInstantLocationByLocationId(queryLocationId);
            if (tempLocation != null) {
                resList.add(tempLocation);
            }
        }
        return resList;
    }

    public Boolean updateWorkingLocations(String locationId, Integer val) {
        if (!StringUtils.isEmpty(locationId)) {
            List<TAppLocation> updateLocations = getLocationListByLocationId(locationId);
            if (updateLocations.size() > 0) {
                return appLocationService.update(new LambdaUpdateWrapper<TAppLocation>()
                    .in(TAppLocation::getLocationId, updateLocations.stream().map(TAppLocation::getLocationId).toList())
                    .set(TAppLocation::getIsWorking, val));
            }
            return false;
        }
        return false;
    }

    /**
     * 根据料号获取物料信息
     * @param goodsId 料号
     * @return 物料信息
     */
    public TAppGoods getInstantGoodsByGoodsId(String goodsId) {
        if (instantGoodsMap.isEmpty()) {
            if (!initInstantGoodsMap()) {
                log.error("物料缓存失败，请尝试重启程序。");
                return null;
            }
        }
        return instantGoodsMap.get(goodsId);
    }

    /**
     * 缓存物料信息
     * @return 缓存结果
     */
    public boolean initInstantGoodsMap() {
        instantGoodsMap.clear();
        try {
            // 获取到所有的配置
            List<TAppGoods> goodsList = appGoodsService.list();
            if (!goodsList.isEmpty()) {
                for (TAppGoods appGoods : goodsList) {
                    instantGoodsMap.put(appGoods.getGoodsId(), appGoods);
                }
            }
            log.info("缓存物料信息成功。");
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
