package com.wms_main.service.controller.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wms_main.dao.ITAppLocationService;
import com.wms_main.model.dto.query.LocationQuery;
import com.wms_main.model.dto.response.wms.BaseWmsApiResponse;
import com.wms_main.model.dto.response.wms.WmsApiResponse;
import com.wms_main.model.po.TAppLocation;
import com.wms_main.model.vo.wms.LocationVo;
import com.wms_main.model.vo.wms.PageVo;
import com.wms_main.repository.utils.StringUtils;
import com.wms_main.service.controller.ILocationControllerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 库位控制类服务实现
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class LocationControllerServiceImpl implements ILocationControllerService {
    private final ITAppLocationService appLocationService;// 库位服务

    /**
     * 实现
     * @param locationQuery 查询参数
     * @return 处理结果
     */
    @Override
    //@Transactional(rollbackFor = Exception.class)
    public BaseWmsApiResponse genLocations(LocationQuery locationQuery) {
        List<TAppLocation> locationList = appLocationService.list();
        List<TAppLocation> newLocationList = new ArrayList<>();
        for (int row = 1; row <= 6; row++) {
            for (int col = 1; col <= 66; col++) {
                for (int layer = 1; layer <= 16; layer++) {
                    if (row == 1 && layer == 16){
                        continue;
                    }
                    String locationId = "A" + StringUtils.padLeft(String.valueOf(row), "", 2)
                            + "-" + StringUtils.padLeft(String.valueOf(col), "0", 2)
                            + "-" + StringUtils.padLeft(String.valueOf(layer), "0", 2);
                    TAppLocation newLocation = new TAppLocation(
                            locationId,
                            "",
                            1,
                            layer == 2 ? 1 : 0,
                            0,
                            0,
                            (row + 1)/2,
                            (row + 1)/2,
                            row,
                            col,
                            layer,
                            1,
                            "",
                            1,
                            ""
                    );
                    // 替换原来的 contains 判断
                    boolean exists = locationList.stream()
                            .anyMatch(location -> location.getLocationId().equals(newLocation.getLocationId()));

                    if (exists) {
                        continue;
                    }
                    newLocationList.add(newLocation);
                }
            }
        }
        appLocationService.saveBatch(newLocationList);
        return BaseWmsApiResponse.success("成功创建了" + newLocationList.size() + "个库位。");
    }

    @Override
    public BaseWmsApiResponse deleteLocation() {
        // 构造删除条件：isOccupy 不等于 1
        LambdaQueryWrapper<TAppLocation> queryWrapper = new LambdaQueryWrapper<TAppLocation>()
                .ne(TAppLocation::getIsOccupy, 1);  // ne 表示不等于 (!=)

        // 执行删除操作
        boolean result = appLocationService.remove(queryWrapper);

        if (result) {
            return BaseWmsApiResponse.success("成功删除所有未被占用的库位");
        } else {
            return BaseWmsApiResponse.error("删除库位失败");
        }
    }


    /**
     * 查询库位信息（分页）---实现
     * @param locationQuery 查询参数
     * @return 查询结果
     */
    @Override
    public WmsApiResponse<PageVo<LocationVo>> queryLocationsByPage(LocationQuery locationQuery) {
        if (locationQuery == null) {
            return WmsApiResponse.error("查询参数不能为NULL", null);
        }
        Page<TAppLocation> page = locationQuery.toMpPage();
        LambdaQueryWrapper<TAppLocation> lambdaQueryWrapper = new LambdaQueryWrapper<TAppLocation>()
                .like(StringUtils.isNotEmpty(locationQuery.getVehicleId()), TAppLocation::getVehicleId, locationQuery.getVehicleId())
                .like(StringUtils.isNotEmpty(locationQuery.getLocationId()), TAppLocation::getLocationId, locationQuery.getLocationId())
                .eq(locationQuery.getIsOccupy() != null, TAppLocation::getIsOccupy, locationQuery.getIsOccupy())
                .eq(locationQuery.getIsLock() != null, TAppLocation::getIsLock, locationQuery.getIsLock());
        Page<TAppLocation> poPage = appLocationService.page(page, lambdaQueryWrapper);

        PageVo<LocationVo> pageVo = PageVo.of(poPage, LocationVo::of);
        return WmsApiResponse.success("查询库位成功", pageVo);
    }
    
    /**
     * 获取所有库位信息---实现
     * @return 库位列表
     */
    @Override
    public WmsApiResponse<List<LocationVo>> getAllLocations() {
        // 获取所有库位数据
        List<TAppLocation> locationList = appLocationService.list();
        
        // 将PO对象转换为VO对象
        List<LocationVo> locationVoList = locationList.stream()
                .map(LocationVo::of)
                .toList();
                
        return WmsApiResponse.success("获取所有库位成功", locationVoList);
    }
}
