package com.tuoheng.admin.service.goods.query;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.entity.domain.Goods;
import com.tuoheng.admin.entity.domain.Warehouse;
import com.tuoheng.admin.entity.request.goods.QueryGoodsListByWarehouseIdRequest;
import com.tuoheng.admin.enums.MarkTypeEnum;
import com.tuoheng.admin.mapper.GoodsMapper;
import com.tuoheng.admin.mapper.WarehouseMapper;
import com.tuoheng.common.exception.ServiceException;
import com.tuoheng.common.utils.JsonResult;
import com.tuoheng.system.entity.User;
import com.tuoheng.system.utils.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 根据仓库ID查询物质表业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-11-22
 */
@Slf4j
@Service
public class QueryGoodsListByWarehouseIdService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private WarehouseMapper warehouseMapper;

    public JsonResult getListByWarehouseId(QueryGoodsListByWarehouseIdRequest request) {
//        log.info("进入查询物质列表业务");
        User user = ShiroUtils.getUserInfo();
        Integer tenantId = user.getTenantId();
        request.setTenantId(tenantId);

        JsonResult result = this.check(request);
        if (0 != result.getCode()) {
            log.info("进入查询物质列表业务：校验失败：{}", result.getMsg());
            return result;
        }
        List<Goods> cameraList = goodsMapper.getListByWarehouseId(request);
        if (CollectionUtil.isEmpty(cameraList)) {
            log.info("物质列表数据为空");
        }
        return JsonResult.success(cameraList);
    }

    /**
     * 检查参数
     *
     * @param request
     * @return
     */
    private JsonResult check(QueryGoodsListByWarehouseIdRequest request) {
        if (ObjectUtil.isNull(request.getWarehouseId())) {
            log.info("仓库ID为空, warehouseId:{}", request.getWarehouseId());
            throw new ServiceException("仓库ID为空");
        }
        Warehouse warehouse = warehouseMapper.selectOne(new LambdaQueryWrapper<Warehouse>()
                            .eq(Warehouse::getTenantId, request.getTenantId())
                            .eq(Warehouse::getMark, MarkTypeEnum.VALID.getCode())
                            .eq(Warehouse::getId, request.getWarehouseId()));
        if (ObjectUtil.isNull(warehouse)) {
            log.info("仓库不存在, warehouseId:{}", request.getWarehouseId());
            throw new ServiceException("仓库不存在");
        }
        return JsonResult.success();
    }

}
