package com.ruoyi.app.service.impl;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.app.domain.AppLocation;
import com.ruoyi.app.mapper.AppLocationMapper;
import com.ruoyi.app.service.IAppLocationService;
import com.ruoyi.common.constant.AppConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-14
 */
@Service
public class AppLocationServiceImpl implements IAppLocationService {
    @Autowired
    private AppLocationMapper appLocationMapper;

    /**
     * 查询【请填写功能名称】
     *
     * @param locationId 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public AppLocation selectAppLocationByLocationId(String locationId) {
        return appLocationMapper.selectAppLocationByLocationId(locationId);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param appLocation 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<AppLocation> selectAppLocationList(AppLocation appLocation) {
        return appLocationMapper.selectAppLocationList(appLocation);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param appLocation 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertAppLocation(AppLocation appLocation) {
        return appLocationMapper.insertAppLocation(appLocation);
    }

    /**
     * 批量保存数据
     *
     * @param appLocationList 数据列表
     * @return 结果
     */
    @Override
    public int insertAppLocationBatch(List<AppLocation> appLocationList) {
        if (appLocationList == null || appLocationList.isEmpty()) {
            return 0;
        }
        return appLocationMapper.insertAppLocationBatch(appLocationList);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param appLocation 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateAppLocation(AppLocation appLocation) {
        return appLocationMapper.updateAppLocation(appLocation);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param locationIds 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteAppLocationByLocationIds(String[] locationIds) {
        return appLocationMapper.deleteAppLocationByLocationIds(locationIds);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param locationId 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteAppLocationByLocationId(String locationId) {
        return appLocationMapper.deleteAppLocationByLocationId(locationId);
    }

    /**
     * 请求库位
     *
     * @param equipmentId 设备号
     * @return 可用库位
     */
    @Override
    public AppLocation requestLocation(int equipmentId) {
        // 查询到所有的库位
        AppLocation locationQuery = new AppLocation();
        locationQuery.setEquipmentId(equipmentId);
        List<AppLocation> appLocationList = appLocationMapper.selectAppLocationList(locationQuery);
        if (appLocationList == null || appLocationList.isEmpty()) {
            return null;
        }
        // 结果库位
        AppLocation resultLocation = null;
        // 可用库位列表
        List<AppLocation> availableLocationList = appLocationList.stream().filter(item ->
                item.getIsWorking() == 0 && item.getIsLock() == 0 && item.getLocationStatus() == 0).sorted(Comparator
                .comparingInt(AppLocation::getwCol).thenComparingInt(AppLocation::getwLayer).thenComparingInt(AppLocation::getwDepth)).collect(Collectors.toList());
        // 排序
        for (AppLocation appLocation : availableLocationList) {
            if (appLocation.getIsWorking() == 1 || appLocation.getIsLock() == 1 || appLocation.getLocationStatus() == 1) {
                continue;
            }
            if (isMaxDepthAvailable(appLocationList, appLocation)) {
                resultLocation = appLocation;
                break;
            }
        }
        return resultLocation;
    }

    @Override
    @Transactional
    public String sendLocation() {
        AppLocation appLocation = new AppLocation();
        appLocation.setLocationStatus(0);
        appLocation.setIsLock(0);
        //查询可用库位
        List<AppLocation> appLocations = appLocationMapper.selectAppLocationList(appLocation);
        if (appLocations == null || appLocations.isEmpty()) {
            throw new RuntimeException("库位已满");
        }
        //筛选深度
        List<AppLocation> collect = appLocations.stream().filter(l -> l.getwDepth().equals(2)).collect(Collectors.toList());
        List<AppLocation> collect1 = appLocations.stream().filter(l -> l.getwDepth().equals(1)).collect(Collectors.toList());
        //定义库位
        String locationId = null;
        if (ObjectUtil.isNotEmpty(collect)) {
            locationId = collect.get(0).getLocationId();
        } else {
            locationId = collect1.get(0).getLocationId();
        }
        AppLocation location = new AppLocation();
        location.setLocationId(locationId);
        location.setLocationStatus(1);
        //更新库位为任务中
        int i = appLocationMapper.updateAppLocation(location);
        if (i == 0) {
            throw new RuntimeException("库位更新失败");
        }
        return locationId;

    }

    /**
     * 是否是最内层可用库位
     *
     * @param appLocationList 库位列表
     * @param appLocation     库位
     * @return 结果
     */
    boolean isMaxDepthAvailable(List<AppLocation> appLocationList, AppLocation appLocation) {
        // 验证库位列表
        if (appLocationList == null || appLocationList.isEmpty()) {
            return false;
        }
        // 验证待查库位
        if (appLocation == null) {
            return false;
        }
        // 查询到排列层对应的库位列表
        List<AppLocation> diffDepthLocationList = appLocationList.stream().filter(item ->
                Objects.equals(item.getwRow(), appLocation.getwRow()) &&
                        Objects.equals(item.getwCol(), appLocation.getwCol()) &&
                        Objects.equals(item.getwLayer(), appLocation.getwLayer()) &&
                        !Objects.equals(item.getwDepth(), appLocation.getwDepth())).collect(Collectors.toList());
        // 结果
        boolean result = true;
        for (AppLocation diffDepthLocation : diffDepthLocationList) {
            if (diffDepthLocation.getIsWorking() == 1) {
                result = false;
                break;
            }
            // 深度低的库位锁定或者占用
            if (diffDepthLocation.getwDepth() < appLocation.getwDepth()) {
                if (diffDepthLocation.getIsLock() == 1 || diffDepthLocation.getLocationStatus() == 1) {
                    result = false;
                    break;
                }
            }
            // 深度高的库位未锁定或者空闲
            if (diffDepthLocation.getwDepth() > appLocation.getwDepth()) {
                if (diffDepthLocation.getIsLock() == 0 && diffDepthLocation.getLocationStatus() == 0) {
                    result = false;
                    break;
                }
            }
        }
        return result;
    }

    public Map<String, Integer> countAvailable() {
        return appLocationMapper.countAvailableStock();
    }

    @Override
    public void changeIsEnableStatus(String[] locationIds) {
        List<AppLocation> appLocationList = appLocationMapper.selectAppLocationListByLocationIds(locationIds);
        if (CollectionUtil.isNotEmpty(appLocationList)) {
            appLocationList.forEach(appLocation -> {
                Integer oldIsEnabled = appLocation.getIsEnable();
                if (AppConstants.LOCATION_STATUS_ENABLE.equals(oldIsEnabled)) {
                    appLocation.setIsEnable(AppConstants.LOCATION_STATUS_DISABLE);
                }else if (AppConstants.LOCATION_STATUS_DISABLE.equals(oldIsEnabled)) {
                    appLocation.setIsEnable(AppConstants.LOCATION_STATUS_ENABLE);
                }
                appLocationMapper.updateAppLocation(appLocation);
            });
        }
    }

    @Override
    public List<AppLocation> selectFreeLoc() {
        return appLocationMapper.selectFreeLoc();
    }
}
