/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.stocks.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.stocks.entity.StockInfo;
import com.tofly.stocks.entity.Store;
import com.tofly.stocks.service.StockInfoService;
import com.tofly.stocks.service.StoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tofly.stocks.mapper.StoreMapper;

import java.util.Arrays;
import java.util.List;

/**
 * 库存仓库表
 *
 * @author admin
 * @date Fri Nov 25 00:00:00 CST 2022
 */
@Service("storeService")
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store> implements StoreService {

    @Autowired
    private StockInfoService stockInfoService;

    /**
     * 检查名称是否存在，用于修改和新增
     * @param store
     * @return
     */
    public boolean isExist(Store store) {

        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("WATERWORKS_ID", store.getWaterworksId());
        queryWrapper.eq("STORE_NAME", store.getStoreName());

        if (store.getId()!=null && store.getId()>0) {
            queryWrapper.ne("ID", store.getId());
        }
        Integer count = baseMapper.selectCount(queryWrapper);

        if (count > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean saveStore(Store store) {
        if(isExist(store)){
            throw new RuntimeException("该水厂下仓库名称已存在，不能新增");
        }
        return this.save(store);
    }

    @Override
    public boolean editStore(Store store) {
        if(isExist(store)){
            throw new RuntimeException("该水厂下仓库名称已存在，不能修改");
        }
        return this.updateById(store);
    }

    @Override
    public boolean deleteByIds(String ids) {
        List<String> lstIds = Arrays.asList(ids.split(","));

      /*  QueryWrapper<StockInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.in("STORE_ID",lstIds);*/
        Integer count=stockInfoService.count(Wrappers.<StockInfo>lambdaQuery()
                .in(StockInfo::getStoreId,lstIds));
        if(count>0){
            throw new RuntimeException("选择的仓库已有库存记录，不能删除");
        }

        return this.removeByIds(lstIds);
    }
}
